题目

猜想:对于任意大于1的自然数n,若n为奇数,则将n变为3n+1,否则变为n的一半。 经过若干次这样的变换,一定会使n变为1。例如,3→10→5→16→8→4→2→1。

解答

很简单的重复性程序,没什么技术含量。

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    int j = 0;

    while (n > 1)
    {
        if (n % 2 == 1)
        {
            j++;
            n = 3 * n + 1;
            continue;
        }
        else
        {
            j++;
            n = n / 2;
            continue;
        }
    }

    cout << j;
    return 0;
}

但是,为了防止数据溢出,我们可以把变量改为 long

#include <iostream>
using namespace std;

int main()
{
    long n;
    cin >> n;
    int j = 0;

    while (n > 1)
    {
        if (n % 2 == 1)
        {
            j++;
            n = 3 * n + 1;
            continue;
        }
        else
        {
            j++;
            n = n / 2;
            continue;
        }
    }

    cout << j;
    return 0;
}

祝各位读者早日成为神牛牪犇!