3n+1解决方案给出错误的答案

3n+1 solution giving wrong answer

本文关键字:答案 错误 出错 解决方案 3n+1      更新时间:2023-10-16

这是我对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 %lldn", i, j, max);
  }
  return 0;
}

您的process()函数将填充globalmap,使得 1 的周期长度为 1,但您的 cyclelength 函数如果传入 ll = 1ans = 0 返回 0 的周期长度。

因此,在以下输入上:

1 1
1 2

您的程序将输出:

1 1 0
1 2 2

这似乎是你的sol'n的症结所在。

如果 i>j,您的解决方案将不起作用。

尝试从 i,j 的最小值迭代到 i,j 的最大值。

请注意,i 和 j

必须按原始顺序打印,因此如果它们顺序错误,请不要只是交换 i 和 j。