这是我对给出错误答案的 3n+1 问题的解决方案。自从过去 5 天以来,我已经在这个安静的环境中挣扎了很多次。请帮助我找出解决方案中的问题。我使用了尾递归,并且还存储了一张地图来跟踪 2 的幂,以便更快地找到答案。问题的链接是编程挑战 - 3n + 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;
}