Logo 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

  equation32896

Section gif presents a recursive function 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_inline68703.

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

gather32906

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

  equation32914

Program gif defines the function Fibonacci which implements directly Equation gif. Given n>1 it computes tex2html_wrap_inline60413 by calling itself recursively to compute tex2html_wrap_inline68715 and tex2html_wrap_inline68717 and then combines the two results as required.

   program32931
Program: Divide-and-Conquer Example--Computing Fibonacci Numbers

To determine a bound on the running time of the Fibonacci routine in Program gif we assume that T(n) is a non-decreasing function. I.e., tex2html_wrap_inline68721 for all tex2html_wrap_inline59533. Therefore tex2html_wrap_inline68725. 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 routine is upper-bounded by T(n) where

  equation32940

Equation gif is easily solved using repeated substitution:

eqnarray32946

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


next up previous contents index

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