Q100 : The 3n + 1 problem

// Accepted after 6 attempts (How tiring)

#include<iostream>
#include<cstdlib>
#include<algorithm>

using namespace std;

int c_length(int num);

int main(int argc, char* argv[])
{
    int n , m;
    while(cin >> n >> m)
    {
        cout << n << " " << m << " ";

        if( m > n )
            swap(m,n);

        int p = 0;

        for(int i = m; i <= n; i++)
        {
            int a = c_length(i);
            if(a > p)
                p = a;
        }
        cout << p << endl;
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

int c_length(int num)
{
    int count = 1;
    while(num != 1)
    {
        count++;
        if(num % 2 != 0)
            num = num * 3 + 1;
        else
            num /= 2;
    }
    return count;
}

Leave a Reply