Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n <- 3n + 1
5. else n <- n / 2
6. GOTO 2
Sample Input
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n <- 3n + 1
5. else n <- n / 2
6. GOTO 2
Sample Input
1 10 100 200 201 210 900 1000
Sample Output
1 10 20 100 200 125 201 210 89 900 1000 174
递归求计算的次数,定义全局变量计数。
ps:这还并不是一个算法,因为你无法证明这个算法的有穷性,无法找出一个一定可以结束循环的数字,不能证明这个数字有还是没有。
这个题的坑就在于数字的大小(只用int是不够的)和输入输出。
输出的m,n 必须和输入的m,n相同,所以就必须定义max_num和min_num循环找出最大的cycle_num
C学的太浅,只能这么做了。
#include <stdio.h>
#include <string.h>
int val[1000000];
long long int con = 0;
long long int fun(long long int n)
{
if(n == 1){
con ++;
return con;
}
else if(!(n % 2)){
n /= 2;
con ++;
fun(n);
}
else if(n % 2){
n = 3 * n + 1;
con ++;
fun(n);
}
}
int main(void)
{
long long int m, n, j, max_num, min_num;
memset(val,0, sizeof(val));
while(scanf("%lld%lld", &m, &n) != EOF){
long long int i, num = 0;
long long int max = 0;
if(m > n){
max_num = m;
min_num = n;
}
else{
max_num = n;
min_num = m;
}
for(i = min_num;i <= max_num; i++){
con = 0;
if(val[i] != 0)
num = val[i];
else{
num = fun(i);
val[i] = num;
}
if(num > max) max = num;
}
printf("%lld %lld %lld\n", m, n, max);
}
return 0;
}