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.
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.
Time Complexity: Hence the time taken by recursive Fibonacci is O(2^n) or exponential.
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.
Recursive Algorithm This is probably the most intuitive approach, since the Fibonacci Sequence is, by definition, a recursive relation.
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..
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.
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