问题
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
. 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];
}
}
}
回答1:
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++. 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:
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
. So, I am assuming that the size of array a
is atleast n
. The value of n
that is mentioned in the question is very large. 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
).
Finally, the complexity of your program is O(n)
. There is a technique to calculate n_th fibonacci number in O(log(n))
time. 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.
来源:https://stackoverflow.com/questions/38554793/finding-the-fibonacci-number-of-large-number