I want to stress quantitatively a very annoying property of the recursive algorithm.
When you call fib(1)
, or fib(2)
, the function returns immediately, so that the number of calls performed is exactly 1
in both cases. We write c(1) = c(2) = 1
, where c(n)
is the number of calls performed to compute fib(n)
.
When you call fib(n)
with n > 2
, you call indirectly fib(n-1)
and fib(n-2)
, for a total number of calls which is 1 + c(n-1) + c(n-2)
.
So c(n)
is defined by the recurrence
c(n) = c(n-1) + c(n-2) + 1,
c(1) = c(2) = 1
The solution is called the Leonardo numbers (https://oeis.org/A001595).
Given the form of the recurrence, you easily see that these numbers exceed the Fibonacci numbers so that its takes more recursive function calls to compute the Nth Fibonacci number than the value of the number itself. And as the Fibonacci numbers grow exponentially, so does the number of calls.
So it's not just "more recursive calls", it is "massively more recursive calls". This makes the method horribly inefficient and impractical for large n
.
Fortunately, there is a simple way to compute the numbers iteratively by just applying the recurrence (given in other answers).
Also of interest is the direct formula
Fn = φ^n/√5
to be rounded to the nearest integer, where φ
is the Golden Ratio.