任给一个自然数,若为偶数则除以2,若为奇数则乘3加1,得到一个新的自然数后,按照上面的法则继续演算,若干次后得到的结果必然为1。请编程进行验证,最后输出进行演算的次数。
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "input number: ";
cin >> n;
int count = 0;
for (int i = 1; i; i++)
{
if (n % 2 == 0)
{
n = n / 2;
count++;
}
else
{
n = 3 * n + 1;
count++;
}
if (n == 1)
break;
}
cout << "n=" << n << endl;
cout << "count=" << count;
return 0;
}