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.
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.
You can do a pretty fast version of recursive Fibonacci by using memoization (meaning: storing previous results to avoid recalculating them). for example, here's a proof of concept in Python, where a dictionary is used for saving previous results:
It returns quickly for input values that would normally block the "normal" recursive version. Just bear in mind that an
int
data type won't be enough for holding large results, and using arbitrary precision integers is recommended.A different option altogether - rewriting this iterative version ...
... as a tail-recursive function, called
loop
in my code:An example in JavaScript that uses recursion and a lazily initialized cache for added efficiency: