Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Example-Computing Fibonacci Numbers

 

The Fibonacci numbers  are given by following recurrence

  equation32690

Section gif presents a recursive method to compute the Fibonacci numbers by implementing directly Equation gif. (See Program gif). The running time of that program is shown to be tex2html_wrap_inline67704.

In this section we present a divide-and-conquer style of algorithm for computing Fibonacci numbers. We make use of the following identities

gather32700

for tex2html_wrap_inline58801. (See Exercise gif). Thus, we can rewrite Equation gif as

  equation32708

Program gif defines the method Fibonacci which implements directly Equation gif. Given n>1 it computes tex2html_wrap_inline59641 by calling itself recursively to compute tex2html_wrap_inline67716 and tex2html_wrap_inline67718 and then combines the two results as required.

   program32725
Program: Divide-and-conquer Example--computing Fibonacci numbers.

To determine a bound on the running time of the Fibonacci method in Program gif we assume that T(n) is a non-decreasing function. That is, tex2html_wrap_inline67722 for all tex2html_wrap_inline58757. Therefore tex2html_wrap_inline67726. Although the program works correctly for all values of n, it is convenient to assume that n is a power of 2. In this case, the running time of the method is upper-bounded by T(n) where

  equation32734

Equation gif is easily solved using repeated substitution:

eqnarray32740

Thus, T(n)=2n-1=O(n).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.