AOJ-0158 : Collatz's Problem
正の整数nに対し、
- n が偶数の時は 2 で割る。
- n が奇数の時は 3 倍し、1 を足す。
いずれは結果が1になるのというコラッツの予想というものがある。
その問題をプログラムするという問題
サンプルには入力1というものがないが、1のときのケースを想定していないと
Wrong Answerになってしまう場合があるので注意。
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0158 #include<iostream> #include<map> #include<vector> #include<algorithm> #include<cmath> #include<climits> #include<ctime> #include<cstring> #include<numeric> #define ALL(v) (v).begin(),(v).end() #define REP(i,p,n) for(int i=p;i<(int)(n);++i) #define rep(i,n) REP(i,0,n) #define dump(a) (cerr << #a << "=" << (a) << endl) #define DUMP(list) cout << "{ "; for(auto nth : list){ cout << nth << " "; } cout << "}" << endl; using namespace std; int calc(int n){ return (n % 2 == 0) ? n/2 : 3*n+1 ; } int main() { int N; while(cin >> N && N) { int tmp=N, cnt=0; while(true) { if(tmp == 1){ break; } cnt++; tmp = calc(tmp); } cout << cnt << endl; } return 0; }