Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving a Fibonacci like recurrence in log n time

Tags:

algorithm

math

Finding the nth term in Fibonacci series f(n) = f(n-1) + f(n-2) can be solved in O(n) time by memoization.

A more efficient way would be to find the nth power of matrix [ [1,1] , [1,0] ] using divide and conquer to solve the Fibonacci in log n time.

Is there similar approach which can be followed for f(n) = f(n-1) + f(n-x) + f(n-x+1) [ x is some constant ].

Just be storing previous x elements, this can solved in O(n) time.

Is there a better way to solve this recursion.

like image 348
elricL Avatar asked Oct 07 '11 10:10

elricL


2 Answers

As you are already suspecting, this will work very similar. Use the n-th power of the x * x matrix

|1 0 0 0  .... 1 1|
|1 
|  1
|    1
|      1
|        1
...................
...................
|          ... 1 0|

This is easy to understand if you multiply this matrix with the vector

f(n-1), f(n-2), ... , f(n-x+1), f(n-x)

which results in

f(n), f(n-1), ... , f(n-x+1)

Matrix exponentiation can be done in O(log(n)) time (when x is considered to be constant).

For the Fibonacci recurrence, there is also a closed formula solution, see here http://en.wikipedia.org/wiki/Fibonacci_number, look for Binet's or Moivre's formula.

like image 184
Doc Brown Avatar answered Oct 16 '22 20:10

Doc Brown


You may want to look into Tribonacci numbers (and other generalizations of Fiboniacci numbers.) They have been studied quite extensively. See e.g. Generalizations of Fibonacci numbers

like image 34
user980473 Avatar answered Oct 16 '22 18:10

user980473