您的位置:首页 > 其它

1001. 害死人不偿命的(3n+1)猜想 (15)

2017-01-01 11:22 441 查看

1001. 害死人不偿命的(3n+1)猜想 (15)

卡拉兹(Callatz)猜想:

对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。这样一直反复砍下去,最后一定在某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……

我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1?

输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。

输出格式:输出从n计算到1需要的步数。

输入样例: 3

输出样例: 5

时间限制 400 ms

内存限制 65536 kB

代码长度限制 8000 B

判题程序 Standard

作者 CHEN, Yue

下边的测试用时和内存仅供参考,因为每次提交代码可能会因为测试用例的不同导致用时和内存都不同,所以仅供参考。

 

//Solution 1 @52Heartz
#include<stdio.h>
int main()
{
int num=0,n,judge;
scanf("%d",&n);
while(n!=1)
{
judge = n%2;
if( judge == 0)
{ n=n/2;
num++;}
else
{ n=(3*n+1)/2;
num++;}
}
printf("%d",num);

return 0;
}


用时2ms
内存256kB
//Solution 2 @ssccinng
#include<stdio.h>
int main(){
int cnt = 0;
int x;
scanf("%d",&x);
if(x <= 1000){
while(x != 1){
if(x % 2 == 0){
x /= 2;
}else{
x = (3*x + 1)/2;
}
cnt++;
}
}
printf("%d",cnt);
return 0;
}


用时5ms
内存384kB
//Solution 3 @L_Aster
#include <stdio.h>
int main(){
int n,c=0;
scanf("%d",&n);
while(n!=1){
n=(n%2==0)?n/2:(3*n+1)/2;
++c;
}
printf("%d",c);
return 0;
}


用时7ms
内存256kB
//Solution 4 @柳婼
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
while (n != 1) {
if (n % 2 != 0) {
n = 3 * n + 1;
}
n = n / 2;
count++;
}
cout << count;
return 0;
}


用时4ms
内存384kB
//Solution 5 @FlyRush
//C/C++实现
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
int n;
scanf("%d", &n);
int count = 0;
while(n != 1){
if(n % 2 != 0){
n = (3 * n + 1) / 2;
count ++;
}
else{
n /= 2;
count ++;
}
}
printf("%d\n", count);
return 0;
}


用时5ms
内存384kB
//Solution 6 @FlyRush
//Java实现
import java.util.Scanner;
public class Main {

public static void main(String []args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int count = 0;
if(n > 0 && n<=1000) {
while (n != 1) {
if (n % 2 == 0) {
count++;
n = n / 2;
} else {
count++;
n = (3 * n + 1) / 2;
}
}
}
System.out.println(count);
}
}


这个测试结果说是返回非0,我还不会Java,之后学会了再来更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: