I was wondering about how can one find the nth term of fibonacci sequence for a very large value of n say, 1000000. Using the grade-school recurrence equation fib(n)=fib(n-1)+fib(n-2)
, it takes 2-3 min to find the 50th term!
After googling, I came to know about Binet's formula but it is not appropriate for values of n>79 as it is said here
Is there an algorithm to do so just like we have for finding prime numbers?
Using the grade-school recurrence equation fib(n)=fib(n-1)+fib(n-2) , it takes 2-3 min to find the 50th term!
We have only defined the nth Fibonacci number in terms of the two before it: the n-th Fibonacci number is the sum of the (n-1)th and the (n-2)th. So to calculate the 100th Fibonacci number, for instance, we need to compute all the 99 values before it first - quite a task, even with a calculator!
The matrix is multiplied n time because then only we can get the (n+1)th Fibonacci number as the element at the row and the column (0, 0) in the resultant matrix. If we apply the above method without using recursive matrix multiplication, then the Time Complexity: O(n) and Space Complexity: O(1) .
You can use the matrix exponentiation method (linear recurrence method). You can find detailed explanation and procedure in this blog. Run time is O(log n).
I don't think there is a better way of doing this.
You can save a lot time by use of memoization. For example, compare the following two versions (in JavaScript):
Version 1: normal recursion
var fib = function(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); };
Version 2: memoization
A. take use of underscore library
var fib2 = _.memoize(function(n) { return n < 2 ? n : fib2(n - 1) + fib2(n - 2); });
B. library-free
var fib3 = (function(){ var memo = {}; return function(n) { if (memo[n]) {return memo[n];} return memo[n] = (n <= 2) ? 1 : fib3(n-2) + fib3(n-1); }; })();
The first version takes over 3 minutes for n = 50 (on Chrome), while the second only takes less than 5ms! You can check this in the jsFiddle.
It's not that surprising if we know version 1's time complexity is exponential (O(2N/2)), while version 2's is linear (O(N)).
Version 3: matrix multiplication
Furthermore, we can even cut down the time complexity to O(log(N)) by computing the multiplication of N matrices.
where Fn denotes the nth term of Fibonacci sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With