本文主要是介绍694 - The Collatz Sequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- Step 1:
- Choose an arbitrary positive integer A as the first item in the sequence. Step 2:
- If A = 1 then stop. Step 3:
- If A is even, then replace A by A / 2 and go to step 2. Step 4:
- If A is odd, then replace A by 3 * A + 1 and go to step 2.
简单题。唯一值得一提的是int有可能越界导致超时(死循环),用long来保存。
#include<stdio.h>
int main()
{
int count=1,sum;
long long A,L,temp;
while(scanf("%lld%lld",&A,&L))
{
if(A<0&&L<0)break;
sum=1;
temp=A;
while(A!=1)
{
if(A%2!=0)
{
A=(A*3+1)/2;
if(A*2>L)break;
sum+=2;
}
else
{
A/=2;
sum++;
}
}
printf("Case %d: A = %lld, limit = %lld, number of terms = %d\n",count++,temp,L,sum);
}
return 0;
}
这篇关于694 - The Collatz Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!