-2
我試着解決3n + 1問題(UVA 100),這裏是我的代碼,但根據UVA在線評判我的程序給出了錯誤的答案,我的代碼通過了我能想到的所有測試案例,但無法檢測到什麼是錯誤的,請幫我找到錯誤。UVA 3n + 1(prob 100)什麼是我的C++程序錯誤
#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;
}
爲什麼'3 * j + 1'後面有'>> 1'? – 2015-03-19 07:19:43
@Matt,因爲那是在原始代碼中。 – paxdiablo 2015-03-19 07:25:47
好的,我認爲它試圖將兩個步驟壓縮成一個 – 2015-03-19 07:27:07