694 - The Collatz Sequence

来源:互联网 发布:淘宝厚底运动鞋正品店 编辑:程序博客网 时间:2024/05/18 17:56
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;}