The 3n + 1 problem(3n+1猜想)
题目:Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n, terminating when n = 1. For example, the following sequence of numbers will be generated for n = 22: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 It is conjectured (but not yet proven) that this algorithm will terminate at n = 1 for every integer n. Still, the conjecture holds for all integers up to at least 1, 000, 000. For an input n, the cycle-length of n is the number of numbers generated up to and including the 1. In the example above, the cycle length of 22 is 16. Given any two numbers i and j, you are to determine the maximum cycle length over all numbers between i and j, including both endpoints.(输入范围是0~1,000,000)
大概的意思是:给两个整数i,j,从i开始,到j结束,如果n是偶数,则除以2,如果n是奇数,则乘以3加1,最终得到1,这是一个循环。你需要编写程序确定i~j中最大的循环次数。
样例输入
1 10
100 200
201 210
900 1000
样例输出
1 10 20
100 200 125
201 210 89
900 1000 174
思路:很明显,这是一个循环。只需要依次检查i~j范围内的数,得出它们的循环次数即可。值得注意的是,题目里没有说明i和j谁大,所以,当i>j时,需要交换两个数。
下面是代码:
#include<stdio.h>
int cycle(int n)
{
int cnt=1;
do
{
if(n%2==0)
{
n=n/2;
cnt++;
}
else
{
n=n*3+1;
cnt++;
}
}while(n!=1);
return cnt;
}//题目中说的循环
int main()
{
long int a,b,max,i,c=0,temp,x,y;
while(~scanf("%d %d",&a,&b))/*题目的样例
输入是一次输入多组数据,需要用到这个语句,以Ctrl+Z结束*/
{
x=a;
y=b;//记录a,b
if(a>b)
{
temp=a;
a=b;
b=temp;
}//输入a>b时,交换
c=cycle(a);
max=c;
for(i=a+1;i<=b;i++)
{
c=cycle(i);
if(max<c)
max=c;
}//求得最大值
printf("%d %d %d\n",x,y,max);
max=0;//max归零,检查下一组输入数据
}
return 0;
}
由于是第一次写文章,各方面都有所欠缺,还望见谅。