aiheshan

有多自律,才能有多自由

导航

UVa 694 - The Collatz Sequence

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem&problem=635

题目:给出了如下算法;

step 1:选择任意一个正整数A为序列的第一个数;

step 2:如A=1或者A>L,则停止

step 3:如A为偶数,则A=A/2,执行step 2;

step 4:如A为奇数,则A=3A+1,执行step 2;

现在给定初始值A,和限定最大数值L;求从A开始,到A=1||A>L,经过数值个数。

思路: 当A为偶数时,A值减小,如A减小到等于1,则停止。如A为奇数,则A增大,当A>L则停止。

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
   //freopen("input.txt","r",stdin);
   int a1,b1,count,k=0;
   long long a,b,c;
   while(cin>>a1>>b1)
   {
     k++;
     if(a1<=0&&b1<=0)
        break;
     count=1;
     a=a1;b=b1;
     while(a%2==0)
     {
        a=a>>1;
        count++;
     }
     while(1)
     {
       if(a==1)
        break;            
       if(a%2)
        {
          c=3*a+1;
          if(c<=b)
            {
              a=c;count++;
              while(a%2==0)
               {  a=a>>1;
                  count++;
               }
            }
         else
           break;
        }
     }
       cout<<"Case "<<k<<": A = "<<a1<<", limit = "<<b1<<", number of terms = "<<count<<endl;
    }
   return 0;
}

 

posted on 2016-08-04 00:05  aiheshan  阅读(241)  评论(0编辑  收藏  举报