您的位置:首页 > 产品设计 > UI/UE

694 - The Collatz Sequence

2012-04-18 13:26 211 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: