1.
def fib(n):
""" Calculates the nth Fibonacci number recursively """
if n == 1 or n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
2.
The problem is that you're doing a lot of repeated work by calculating
it from the top down. If you look at all of the function calls:
fib(n)
fib(n-1)
fib(n-2)
fib(n-3)
...
fib(n-4)
...
fib(n-3)
fib(n-4)
...
fib(n-5)
...
fib(n-2)
fib(n-3)
...
fib(n-4)
...
At each level, we see that we're recalcating values over and over again.
For example,
- fib(n) calls fib(n-1) and fib(n-2)
- fib(n-1) calls fib(n-2) and fib(n-3)
We'll calculate fib(n-2) two times. As we continue on further, we'll
see even more repetition.
In general, we are more than doubling the amount of work each time n
increases by 2. This results in *exponential* runtime as a function
of n.