简体   繁体   English

寻找大数的斐波那契数

[英]Finding the fibonacci number of large number

I wrote the following program for finding the modulus of large Fibonacci's number. 我编写了以下程序来查找大斐波那契数的模数。 This can solve large numbers but fails to compute in cases like fibo_dynamic(509618737,460201239,229176339) where a = 509618737 , b = 460201239 and N = 229176339 . 这可以解决大量问题,但在fibo_dynamic(509618737,460201239,229176339)这样a = 509618737情况下无法计算,其中a = 509618737b = 460201239N = 229176339 Please help me to make this work. 请帮助我完成这项工作。

long long  fibo_dynamic(long long  x,long long  y,long long  n, long long a[]){
    if(a[n]!=-1){
         return a[n];
    }else{
        if(n==0){
            a[n]=x;
            return x;
        }else if(n==1){
            a[n]=y;
            return y;
        }else {
            a[n]=fibo_dynamic(x,y,n-1,a)+fibo_dynamic(x,y,n-2,a);
            return a[n];
        }
    }
}

The values will overflow because Fibonacci numbers increase very rapidly. 这些值将溢出,因为斐波那契数迅速增加。 Even for the original fibonacci series (where f(0) = 0 and f(1) = 1 ), the value of f(90) is more than 20 digits long which cannot be stored in any primitive data type in C++. 即使对于原始的斐波那契数列(其中f(0) = 0f(1) = 1 ), f(90)的值也超过20位,并且不能以C ++的任何原始数据类型存储。 You should probably use modulus operator (since you mentioned it in your question) to keep values within range like this: 您可能应该使用模运算符(因为您在问题中提到了它)将值保持在这样的范围内:

a[n] = (fibo_dynamic(x,y,n-1,a) + fibo_dynamic(x,y,n-2,a)) % MOD;

It is safe to mod the value at every stage because mod operator has the following rule: 它是安全的mod在每一个阶段的价值,因为mod操作有以下规则:

if a = b + c, then:
a % n = ((b % n) + (c % n)) % n

Also, you have employed the recursive version to calculate fibonacci numbers (though you have memoized the results of smaller sub-problems). 同样,您已经使用了递归版本来计算斐波那契数(尽管您已经记住了较小的子问题的结果)。 This means there will be lots of recursive calls which adds extra overhead. 这意味着将有很多递归调用,这增加了额外的开销。 Better to employ an iterative version if possible. 如果可能,最好使用迭代版本。

Next, you are indexing the array with variable n . 接下来,您将使用变量n索引数组。 So, I am assuming that the size of array a is atleast n . 因此,我假设数组a的大小至少为n The value of n that is mentioned in the question is very large. 问题中提到的n的值非常大。 You probably cannot declare an array of such large size in a local machine (considering an integer to be of size 4 bytes , the size of array a will be approximately 874 MB ). 您可能无法在本地计算机中声明如此大的数组(考虑整数为4 bytes ,数组a的大小约为874 MB )。

Finally, the complexity of your program is O(n) . 最后,程序的复杂度为O(n) There is a technique to calculate n_th fibonacci number in O(log(n)) time. 有一种技术可以计算O(log(n))时间中的第O(log(n))斐波那契数。 It is "Solving Recurrence relations using Matrix Exponentiation." 它是“使用矩阵幂求解递归关系”。 Fibonacci numbers follow the following linear recurrence relation: 斐波那契数遵循以下线性递归关系:

f(n) = f(n-1) + f(n-2)   for n >= 2

Read this to understand the technique. 阅读本文以了解技术。

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

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