c++ - 使用 std::map 在 C++ 中递归斐波那契
问题描述
我是 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
任何帮助将不胜感激
解决方案
我通过使用 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
感谢评论中的所有帮助!
推荐阅读
- ios - 仅导入 ARKit 的 iOS Vision 框架
- c - Linux GPSD 比 GPS 鼠标的原始数据更准确
- javascript - 无法读取未定义的属性“草”
- tensorflow - 知识蒸馏是否具有整体效应?
- javascript - 尝试将 javascript 值动态插入到 asp 标签助手元素中
- sql - SQL 连接最佳匹配器
- vuejs3 - 将 Vue.config.js 转换为 vite.config.js 构建路径
- kotlin - kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单
- php - 使用查询构建器和 Symfony 的预订系统
- excel-formula - 确定单元格中的第 4 个字符是数字还是文本