Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out nth fibonacci number for very large 'n'

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?

like image 849
kunal18 Avatar asked Feb 02 '13 11:02

kunal18


People also ask

How do you find the Fibonacci of large 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!

How do you find the nth Fibonacci number?

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!

How do you find the nth Fibonacci number in a Logn time?

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) .


2 Answers

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.

like image 172
Wayne Rooney Avatar answered Nov 09 '22 15:11

Wayne Rooney


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.

matrix

where Fn denotes the nth term of Fibonacci sequence.

like image 33
Hui Zheng Avatar answered Nov 09 '22 14:11

Hui Zheng