POJ 1207 The 3n + 1 problem

C++11 feature version

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const unsigned maximum = 10000;

unsigned loop(unsigned n)
{
    unsigned i = 1;

    while (n != 1)
    {
        i++;
        if (n % 2)
            n = n * 3 + 1;
        else
            n = n / 2;
    }

    return i;
}

int main()
{
    vector<unsigned> v(maximum);

    for (unsigned i = 0; i < maximum; i++)
        v[i] = loop(i + 1);

    int i, j;

    while (cin >> i >> j)
    {
        vector<unsigned>::const_iterator runner = v.cbegin() + (i > j ? i : j);
        vector<unsigned>::const_iterator chaser = v.cbegin() + (i > j ? j : i);

        unsigned maxElem = 0;

        for_each(chaser, runner, [&maxElem](const unsigned e)
        {
            if (e > maxElem)
                maxElem = e;
        });

        cout << maxElem << endl;
    }

    return 0;
}

 

posted @ 2016-01-22 15:28  健康平安快乐  阅读(141)  评论(0编辑  收藏  举报