Now, let's write a function to compute the n-th Fibonacci number. Fibonacci numbers are defined as follows:
fib(1) = 1
fib(2) = 1
fib(3) = fib(2) + fib(1) = 2
fib(4) = fib(3) + fib(2) = 3
fib(5) = fib(4) + fib(3) = 5
fib(6) = fib(5) + fib(4) = 8
...
...
fib(n) = fib(n-1)+fib(n-2)
def fib(n):
if n <= 2:
return 1
return fib(n-1) + fib(n-2)
Note that the base case here is different from the on in fact(n). If the base case had been
if n == 1:
return 1
we'd have a problem computing fib(2), since we'd be trying to compute fib(0), and then fib(-1) and fib(-2), and so on.
Here is the call tree for fib(n):
Calls:
1 levels
\
... ... 1 ...
... ... ... ...
n-2 n-3 n-3 n-4 4
\/ \/ 3
n-1 _ n-2 2
\ / 1
n 0