我在 stackoverflow 等上看到了一些关于3n+1 问题的问题,并尝试修复上述提示以使代码正确。例如,现在我检查是否a > b
。或者我使用long long
而不是简单的int
. 但仍然得到错误的答案。我的回答有什么问题?
我的代码:
#include <iostream>
using namespace std;
int count_steps(long long int num)
{
int counter = 1;
while(num != 1)
{
if (num % 2 == 1)
num = 3*num + 1;
else
num /= 2;
counter++;
}
return counter;
}
int max_between(long long int a , long long int b)
{
int max=0,step;
for(long long int i = a; i <= b; i++)
{
if ((step = count_steps(i)) > max)
max = step;
}
return max;
}
int main()
{
int max=0,a,b,step;
cin >> a;
cin >> b;
if (a >= b)
cout << a << ' ' << b << ' ' << max_between(b,a) << endl;
else
cout << a << ' ' << b << ' ' << max_between(a,b) << endl;
return 0;
}
测试用例:
1 10 (input)
1 10 20 (output)
900 1000 (input)
900 1000 174 (output)
1 1000000 (input)
1 1000000 525 (output)
1000000 1 (input)
1000000 1 525 (output)