无符号长长不会超过第 93 个斐波那契数列?
下面是我为查找第 n 个斐波那契数而编写的代码:
unsigned long long fib(int n)
{
unsigned long long u = 1, v = 1, t;
for(int i=2; i<=n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
虽然算法运行得相当快,但当 n>93 时,输出开始变得异常。我认为/知道这是因为 unsigned long long 的 64 位大小。我是 C++ 新手,但有没有办法解决这个问题,以便我可以获得 fib(9999) 之类的答案?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://gmplib.org/
http://gmplib.org/
使用 bigint 库。网络上有很多(例如,此处和此处)或自行推出。
编辑:自己推出比我预期的要困难得多。算术并不是最难的部分;它以十进制形式打印结果。
Use a bigint library. There are plenty around the web (e.g., here and here) or roll your own.
EDIT: Rolling your own is much more difficult than I expected. The arithmetic isn't the hard part; it's printing out the result in decimal form.
Boost Libraries 是 C++ 标准化人员的工作场所。 使用 C++ boost 库有哪些优点?< /a> 简而言之,如果你用C++开发,你应该有Boost。
Boost 通过 Boost.Multi precision 库。当前后端的选择是:
如果您不想经历安装 GMP(或处理许可问题)的痛苦,或者根本不想将任何东西与您的应用程序一起打包,那么您可以使用第一个,即#include-only。这是一个简单的示例,它就是这样做的:
要编译它,只需确保 Boost 标头位于包含路径中的某个位置。执行生成的程序会产生:
Boost Libraries is where the people who standardize C++ go to play. What are the advantages of using the C++ boost libraries? In short, if you develop with C++, you should have Boost.
Boost, conveniently, provides easy access to multiprecision arithmetic (or “bignums”) with the Boost.Multiprecision library. Current choices of backend are:
If you do not want to go through the grief of installing GMP (or deal with the licensing issues), or just don’t want to package anything alongside your application at all, then you can use the first one, which is #include-only. Here is a simple example that does just that:
To compile that just make sure that the Boost headers are somewhere in your include path. Executing the resulting program produces: