Why does Fibonacci recursive procedure works so long?
This is in OCaml:
let rec fib n = if n<2 then n else fib (n-1) + fib (n-2);;
This is in Mathematica:
Fib[n_] := If[n < 2, n, Fib[n - 1] + Fib[n - 2]]
This is in Java:
public static BigInteger fib(long n) {
if( n < 2 ) {
return BigInteger.valueOf(n);
}
else {
return fib(n-1).add(fib(n-2));
}
}
For n=100 it works for a long time, because, I guess, it traces tree with 2^100 nodes in time.
Although, there are only 100 numbers to generate, so it could consume just 100 memory registers and 100 calculation tacts.
So, execution could be optimized.
What does this task about and how is it solved? Since solution does not implemented in Mathematica it probably doesn’t exist. What about research on this matter?
This is a classic example used to show the value of memoization. So, that’s one approach to make it go faster.
(If you just want to calculate fibonacci quickly, of course it’s extremely easy to rewrite the function to get the answer very fast. Start from 0 and work up to n, passing the previous 2 fibonacci numbers each time.)