Naïve recursive Fibonacci [00QI]
Recall the definition of the Fibonacci numbers: We can directly turn this definition into a recursive function to compute the nth Fibonacci number, but it is extremely slow (in fact, it is \Theta (\varphi ^n)):
# Fibonacci #1: naive recursive algorithm
def fib1(n):
if n <= 1:
return n
else:
return fib1(n-1) + fib1(n-2)Why is it so slow? If we draw the recursion call tree for, say, fib1(5), we can see the problem:
fib1(5) calls fib1(4) and fib1(3); but fib1(4) again calls fib1(3); and so on. fib1(1) ends up being called five times! If we were to start with a bigger number, it would be even worse.
The problem, then, is that fib1 spends a lot of time redundantly recomputing values that have already been computed before.