len函数计算特定值的数链长。循环比较找到最大值即可。
代码如下:
#include <iostream>
using namespace std;
int len(int k)
{
int len = 1;
if (k == 1) return len;
while(k != 1)
{
if (k % 2) k = 3 * k + 1;
else k = k / 2;
len ++;
}
return len;
}
int main()
{
int i,j;
cin >> i >> j;
int max = 0;
for (int k = i;k <= j;k ++)
{
int tem = len(k);
if (max < tem)
max = tem;
}
cout << max << endl;
}