2015年5月22日 星期五

Q100: The 3n + 1 problem

題目資料:http://luckycat.kshs.kh.edu.tw/homework/q100.htm
Hint:  
d%2 d對2取餘數

程式碼:
//Created by yuan_syun on 2015/5/22.
#include <iostream>
using namespace std;

int main()
{
int i, j;
while(cin>>i>>j)
{
int c[1024], tmp, max=0; //先令max最大計數為0,不可設在迴圈外面,這樣才可以reset
cout <<i<<" "<<j<<" ";

if(i>j) //如果輸入i>j,將會對調
{
tmp=j;
j=i;
i=tmp;
}

for(int a=i;a<=j;a++)
{
if(a==1) //如果一開始i=1,將會跳出,往下一個
{c[a]=1;}
else
{
int d=a;
c[a]=1;
while(1)
{
c[a] = c[a] + 1; //計數
if((d%2)==0) //偶數
{d = d/2;}
else //奇數
{d = 3*d+1;}
if(d==1){break;} //如果a=1,將跳出迴圈,進入下一個
}
}
}

for(int b=i;b<=j;b++)
{
if(c[b]>max) //如果有比0大的就取代
{max=c[b];}
}

cout <<max<<endl;

}
return 0;

}

沒有留言:

張貼留言

歡迎指教或發問