简体   繁体   English

计算第 1 百万个斐波那契数

[英]Computing the 1 millionth fibonacci number

I am trying to compute the 1 millionth fibonacci number using the Big Int Library since the number is more than 200,000 digits.我正在尝试使用 Big Int 库计算第 1 百万个斐波那契数,因为该数超过 200,000 位。 I can't seem to fix this problem I am having when taking the sqrt or pow, Big Int can't be assigned to pow or sqrt.我似乎无法解决我在使用 sqrt 或 pow 时遇到的这个问题,Big Int 无法分配给 pow 或 sqrt。

BigInteger Phi = (sqrt(5) + 1) / 2;

BigInteger phi = (sqrt(5) - 1) / 2;

BigInteger PhiSquared = pow(Phi, n);
BigInteger phiSquared = pow(phi, n);

If you want to use a library that can handle big integers, the simplest thing is to get the boost library and use the cpp_int type in the multiprecision library.如果你想使用可以处理大整数的库,最简单的方法是获取boost库并使用多精度库中的cpp_int类型。

Since the multiprecision library is header-file only, this would be one of the simplest ones to use right out-of-box with minimal setup.由于多精度库仅是头文件,因此这将是开箱即用且设置最少的最简单的库之一。

Here is a simple, straightforward implementation that computes the 1 millionth Fibonacci number without using floating point (which could yield inexact results):这是一个简单、直接的实现,它在不使用浮点的情况下计算第 100 万个斐波那契数(这可能会产生不精确的结果):

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
 
int main() {
    using Int = boost::multiprecision::cpp_int;
    Int n1 = 0, n2 = 1;
    Int n3;
    for (int i = 1; i <= 1000000; ++i)
    {
        n3 = n1 + n2;
        n1 = n2;
        n2 = n3;
    }
    std::cout << n3;
}

This took around 40 seconds to complete on an Intel I7 laptop, using Visual Studio 2019 in release mode.使用处于发布模式的 Visual Studio 2019 在 Intel I7 笔记本电脑上完成此过程大约需要 40 秒。

The resulting number is a 208988 digit number.生成的数字是 208988 位数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM