Given nonnegative integer \(n\), we can compute \(f_n\) like so:
f(n) {
if n < 2 then return n
else return f(n-1) + f(n-2)
}
The problem is that this recursive procedure has an exponential running time due to its computing f(k) for those k < n repeatedly.
This can be done by computing f(k) for all k = 0, 1, 2, … in that order. This iterative procedure takes \(O(n)\) additions.
f(n) {
F ← an empty array of length n
F[0] ← 0
F[1] ← 1
for i ← 2 to n do
F[i] ← F[i-1] + F[i-2]
return F[n]
}