使用 std::map 在 C++ 中递归斐波那契数列

时间:2020-12-29 01:34:11

标签: c++ recursion memoization

我是 c++ 的新手,试图拿起绳子,我试图编写一个递归和记忆的斐波那契函数,返回第 n 个斐波那契数,我想使用 std::map 进行记忆,我还写了一个做同样事情的python版本。问题是在数字 94 处,程序的 C++ 版本返回了错误的值,但在那之前它运行良好,有人能指出我正确的方向吗?

#include <iostream>
#include <map>
#define Log(x) std::cout << x << std::endl;

unsigned long long int fib(const int &n)
{
    static std::map<int, unsigned long long int> memo;
    if (n < 3)
        return 1;
    if (memo.count(n) > 0)
        return memo[n];
    memo[n] = fib(n - 1) + fib(n - 2);
    return memo[n];
}

int main(int argc, const char *argv[])
{
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    Log(fib(number));
}

这是运行良好的python版本,

import sys


def fib(n, memo={}):
    if n < 3:
        return 1
    if n in memo:
        return memo[n]
    memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]


sys.setrecursionlimit(10**7)
number = int(input("Enter a number: "))
print(fib(number))

这里是输出:

$ ./executables/fib
Enter a number: 93
12200160415121876738
$ python ./fib.py
Enter a number: 93
12200160415121876738
$ ./executables/fib
Enter a number: 94
1293530146158671551
$ python ./fib.py
Enter a number: 94
19740274219868223167

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我使用 boost 多精度库中的 cpp_int 修复了由于数字太大而无法放入 unsigned long long int(由 tadman 指示的 uint64_t)导致的固定问题。

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
#include <map>

using namespace boost::multiprecision;
using namespace std;
cpp_int fib(const int &n)
{
    static map<int, cpp_int> memo;
    if (n < 3)
        return 1;
    if (memo.count(n) > 0)
        return memo[n];
    memo[n] = fib(n - 1) + fib(n - 2);
    return memo[n];
}

int main()
{
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << fib(number) << endl;
}

它现在工作得很好。

$ ./executables/fib
19740274219868223167

感谢评论中的所有帮助!

相关问题