Precompute a large number of fib(n)
results, and store them as a lookup table inside your algorithm. Bam, free "speed"
Now if you need to compute fib(101)
and you already have fibs 0 to 100 stored, this is just like trying to compute fib(1)
.
Chances are this isn't what this homework is looking for, but it's a completely legit strategy and basically the idea of caching extracted further away from running the algorithm. If you know you're likely to be computing the first 100 fibs often and you need to do it really really fast, there's nothing faster than O(1). So compute those values entirely out of band and store them so they can be looked up later.
Of course, cache values as you compute them too :) Duplicated computation is waste.