UVa 694 - The Collatz Sequence

时间:2023-07-21 19:42:26

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=;
long long a,b,c;
while(cin>>a1>>b1)
{
k++;
if(a1<=&&b1<=)
break;
count=;
a=a1;b=b1;
while(a%==)
{
a=a>>;
count++;
}
while()
{
if(a==)
break;
if(a%)
{
c=*a+;
if(c<=b)
{
a=c;count++;
while(a%==)
{ a=a>>;
count++;
}
}
else
break;
}
}
cout<<"Case "<<k<<": A = "<<a1<<", limit = "<<b1<<", number of terms = "<<count<<endl;
}
return ;
}