Wednesday, July 24, 2013

UVa 100 - The 3n + 1 problem

UVa Problem

#include <iostream>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
   int t1, t2;

   while(cin >> t1)
   {
      cin >> t2;

      int start, end;

      start = t1;
      end = t2;

      if(start > end)
         swap(start, end);

      int maxCycleLen = 1;

      for(int num = start; num <= end; ++num)
      {
         int cycleLen = 1;
         int currNum = num;

         while(currNum != 1)
         {
            if(currNum%2 == 0)
               currNum /= 2;
            else
               currNum = 3 * currNum + 1;

            ++cycleLen;
         }
         maxCycleLen = max(maxCycleLen, cycleLen);
      }

      cout << t1 << " " << t2 << " " << maxCycleLen << endl;
   }

   return 0;
}

No comments:

Post a Comment