Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Fibonacci recursion

Tags:

I'm trying to recall an algorithm on Fibonacci recursion. The following:

public int fibonacci(int n)  {   if(n == 0)     return 0;   else if(n == 1)     return 1;   else     return fibonacci(n - 1) + fibonacci(n - 2); } 

is not what I'm looking for because it's greedy. This will grow exponentially (just look at Java recursive Fibonacci sequence - the bigger the initial argument the more useless calls will be made).

There is probably something like a "cyclic argument shift", where calling previous Fibonacci value will retrieve value instead of calculating it again.

like image 461
ducin Avatar asked Dec 11 '12 19:12

ducin


People also ask

How can you make the Fibonacci sequence faster?

Summary: The two fast Fibonacci algorithms are matrix exponentiation and fast doubling, each having an asymptotic complexity of Θ(logn) bigint arithmetic operations. Both algorithms use multiplication, so they become even faster when Karatsuba multiplication is used.

How long does recursive Fibonacci take?

Time Complexity: Hence the time taken by recursive Fibonacci is O(2^n) or exponential.

Why Fibonacci recursion is slow?

Fibonacci numbers grow exponentially and normally a computer can iterate around 10^8 - 10^9 values of n in one seconds. If you will execute a recursive function, may be the function is taking lots of values because of which the program is executing slowly.

Which algorithm is best for fibonacci series?

Recursive Algorithm This is probably the most intuitive approach, since the Fibonacci Sequence is, by definition, a recursive relation.


2 Answers

maybe like this:

int fib(int term, int val = 1, int prev = 0) {  if(term == 0) return prev;  return fib(term - 1, val+prev, val); } 

this function is tail recursive. this means it could be optimized and executed very efficiently. In fact, it gets optimized into a simple loop..

like image 85
duedl0r Avatar answered Dec 05 '22 00:12

duedl0r


This kind of problems are linear recurrence types and they are solved fastest via fast matrix exponentiation. Here's the blogpost that describes this kind of approach concisely.

like image 43
plesiv Avatar answered Dec 05 '22 00:12

plesiv