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

Example-Generalized Fibonacci Numbers

Consider the problem of computing the generalized Fibonacci numbers  . The generalized Fibonacci numbers of order tex2html_wrap_inline60907 are given by

  equation33286

Notice that the ``normal'' Fibonacci numbers considered in Section gif are the same as the generalized Fibonacci numbers of order 2.

If we write a recursive function that implements directly Equation gif, we get an algorithm with exponential running time. For example, in Section gif it is shown that the time to compute the second-order Fibonacci numbers is tex2html_wrap_inline68703.

The problem with the direct recursive implementation is that it does far more work than is needed because it solves the same subproblem many times. For example, to compute tex2html_wrap_inline68977 it is necessary to compute both tex2html_wrap_inline68979 and tex2html_wrap_inline68981. However, in computing tex2html_wrap_inline68979 it is also necessary to compute tex2html_wrap_inline68981, and so on.

An alternative to the top-down recursive implementation is to do the calculation from the bottom up. In order to do this we compute the series of sequences

eqnarray33304

Notice that we can compute tex2html_wrap_inline68987 from the information contained in tex2html_wrap_inline67646 simply by using Equation gif.

Program gif defines the function Fibonacci which takes two integer arguments n and k and computes the tex2html_wrap_inline58453 Fibonacci number of order k using the approach described above. This algorithm uses an array to represent the series of sequences tex2html_wrap_inline68999. As each subsequent Fibonacci number is computed it is added to the end of the array.

   program33317
Program: Dynamic Programming Example--Computing Generalized Fibonacci Numbers

The worst-case running time of the Fibonacci routine given in Program gif is a function of both n and k:

displaymath68969


next up previous contents index

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