算法入门经典 例题 2-2

题目

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

解答

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}

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