這是我解決N + 1個問題即給予錯誤的答案。自從過去5天以來,我一直在這個安靜的地方掙扎很多次。請幫我解決我的解決方案中的問題。我使用了尾遞歸,並且還存儲了一張地圖來追蹤2的權力以更快地達到答案。 這個問題的鏈接是Programming Challenges - The 3n + 1 problem3N + 1解決方案,使得錯誤的答案
#include <stdio.h>
#include <map>
using namespace std;
#define MAX 1000000
typedef long long int ll;
map<int, int> globalMap;
void process(){
ll i = 1, key = 1, value = 1;
while(value < MAX){
globalMap[value] = key;
key++; value *= 2;
}
return;
}
ll cycleLength(ll n, ll ans){
if(n == 1) return ans;
if(globalMap.find(n) != globalMap.end()) return ans+globalMap[n];
else{
if(n%2){
return cycleLength(3*n+1, ++ans);
}
else return cycleLength(n/2, ++ans);
}
}
int main(){
ll i, j, temp, max=-1;
process();
while(scanf("%lld%lld", &i, &j) != EOF){
max = -1;
for(ll a = i; a <= j; ++a){
temp = cycleLength(a, 0);
if(max < temp) max = temp;
}
printf("%lld %lld %lld\n", i, j, max);
}
return 0;
}
無關你的問題,但也有一對夫婦的其他問題與您的代碼。例如,如果輸入不正確,則使用['scanf'](http://en.cppreference.com/w/cpp/io/c/fscanf)可能會導致問題。另一件看起來很奇怪的事情是爲什麼你要在C++程序中使用'scanf'和'printf'? –
請指定什麼是輸入,什麼是期望的輸出,什麼是實際的輸出,以及(如果仍然不清楚前三個)什麼是你得到的錯誤。 –
至於你的問題,你是否嘗試逐行調試調試器中的代碼?它可能會幫助您找到問題,或者至少將其縮小到某些特定的代碼。另外,對於一些示例輸入,*期望*和*實際*輸出是什麼? –