Wednesday, July 2, 2014

UVa - 100 - The 3n + 1 problem - recursive solution


  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. using namespace std;
  5. int gen(int n){
  6.     int count = 0;
  7.     if(== 1)
  8.         return count = 1;
  9.     if(% 2 == 0){
  10.         return count = 1 + gen(/ 2);
  11.     }
  12.     else{
  13.         return count = 1 + gen(3 * n + 1);
  14.     }
  15. }
  16. int main(){
  17.     int m, n, x, y;
  18.     while(cin >> x >> y){
  19.         cout << x << " " << y << " ";
  20.         m = max(x, y);
  21.         n = min(x, y);
  22.         int mx = 0;
  23.         for(int i = n; i <= m; i++){
  24.             gen(i);
  25.             mx = max(mx,gen(i));
  26.         }
  27.         cout << mx << endl;
  28.     }
  29.     return 0;
  30. }

No comments:

Post a Comment