Thread: fibonacci
View Single Post
Join Date: Oct 2007
Posts: 62
Reputation: Ptolemy is an unknown quantity at this point 
Solved Threads: 8
Ptolemy's Avatar
Ptolemy Ptolemy is offline Offline
Junior Poster in Training

Re: fibonacci

 
0
  #4
Oct 24th, 2007
>What about a purely iterative solution, that does not need the excess
>memory, and is not logically limited in the number of values to display?
That's fine for just printing the sequence. The array is more open to extension though. Let's say you want to write fib(x) where x is the number and the function returns F^N. With the array you can do this:
  1. int fib ( int x )
  2. {
  3. static const int max = 25;
  4. static int n = 2;
  5. static int fibArray[max] = {1,1};
  6.  
  7. while ( n < x ) {
  8. fibArray[n] = fibArray[n - 1] + fibArray[n - 2];
  9. ++n;
  10. }
  11.  
  12. return fibArray[x];
  13. }
At the (minor, in this case) cost of extra storage, you avoid recalculating parts of the sequence that you've already calculated. That's the principle behind the dynamic recursive algorithm.
Reply With Quote