challenge_programming的3n+1问题

#include<stdio.h>
int count(int n)
{
//sum为循环节长度
int sum = 1;
while(n != 1)
{
n = (n%2 == 0) ? n/2 : 3*n+1;
sum++;
}
return sum;
}
int calculate(int i, int j)
{
//n用来遍历从i到j
int n = 0;
//outcome是最终结果
int outcome = 0;
//temp中间变量
int temp = 0;
for(n = i; n <= j; n++)
{
temp = count(n);
if(outcome < temp)
outcome = temp;
}
return outcome;
}
void main()
{
//定义两个变量,表示从i到j的全部数
int i = 0, j = 0;
//将数据读到a和b数组中去
int a[10] = {0}, b[10] = {0};
//n是循环节长度
int n = 0;
//表明是第几组数据
int x = 0;
//中间变量
int temp = 0;
for(x = 0; x < 4; x++)
scanf("%d %d",&a[x],&b[x]);
x = 0;
while (x < 4)
{
i = a[x];
j = b[x];
temp = calculate(i,j);
printf("%d %d %d\n",i,j,temp);
x++;
}
}
相关文章
相关标签/搜索