我尝试解决 3n+1 问题(UVa 100),这是我的代码,但根据 UVa 在线判断我的程序给出了错误的答案,我的代码通过了我能想到的所有测试用例,但无法检测到问题所在帮我找出错误。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> Num;// for Memoization till 1000000
int counter(long int j) {
if(j > 1000000) {
if(j%2 == 1) return(counter((3*j+1)>>1)+2);
else return(counter(j>>1)+1);
}
else {
if(Num[j] != 0) return Num[j];
if(j%2 == 1) Num[j] = counter(3*j+1)+1;
else Num[j] = counter(j>>1)+1;
}
}
int main() {
Num.resize(1000001);//auto initilizes the vector with 0
Num[1] = 1; // set the counter for n = 1 as 1;
int X,Y;
while ( cin >> X >> Y ) {
int x = X , y = Y, mxl = 0;
if(X > Y) swap(X,Y);
for ( long int j = Y; j >= X; --j) {
if(Num[j] == 0) counter(j);
if(mxl < Num[j]) mxl = Num[j];
}
cout << x << " " << y << " " << mxl << endl;
}
return 0;
}