18.04.2013 Views

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Fibonacci numbers<br />

Figure: <strong>The</strong> computation tree for computing Fibonacci numbers recursively<br />

How much time does this algorithm take to compute Fibonacci[n]? Since<br />

, this means that . Since our recursion tree, illustrated in<br />

Figure , has only 0 and 1 as leaves, summing up to such a large number means we must have at least<br />

leaves or procedure calls! This humble little program takes exponential time to run!<br />

In fact, we can do much better. We can calculate in linear time by storing all values. We trade space<br />

for time in the algorithm below:<br />

Fibonacci[n]<br />

For i=1 to n,<br />

Because we evaluate the Fibonacci numbers from smallest to biggest and store all the results, we know<br />

that we have and ready whenever we need to compute . Thus each of the n values is computed<br />

as the simple sum of two integers in total O(n) time, which is quite an improvement over exponential<br />

time.<br />

file:///E|/BOOK/BOOK2/NODE44.HTM (2 of 3) [19/1/2003 1:28:42]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!