Thread: fibonacci
View Single Post
Join Date: Jun 2006
Posts: 1,169
Reputation: Duki has a spectacular aura about Duki has a spectacular aura about Duki has a spectacular aura about 
Solved Threads: 9
Duki's Avatar
Duki Duki is offline Offline
Veteran Poster

Re: fibonacci

 
0
  #8
Oct 25th, 2007
Ok, I got it to work using a pointer. Here's my code.

  
  1. #include <ctime>
  2. #include <iostream>
  3. using namespace std ;
  4.  
  5. int fib ( int ) ;
  6.  
  7. int main ( )
  8. {
  9. clock_t start ;
  10. clock_t end ;
  11.  
  12. cout << "Beginning timer..." << endl ;
  13. start = clock() ;
  14.  
  15. cout << endl ;
  16. for ( int k = 0 ; k < 12 ; k++ )
  17. {
  18. int i = fib ( k ) ;
  19. cout << i << "\t" ;
  20. }
  21.  
  22. cout << endl ;
  23.  
  24. end = clock() ;
  25. cout << "\nThe calculation took " << ( double ( end ) - start ) / CLOCKS_PER_SEC << " seconds.\n" ;
  26.  
  27. cout << "\n\n-- Done --\n\n" ;
  28.  
  29. return 0 ;
  30. }
  31.  
  32. int fib ( int n )
  33. {
  34. int * fibArray = new int[ n ] ;
  35.  
  36. if ( n <= 1 )
  37. return 1 ;
  38. else
  39. {
  40. fibArray[ 0 ] = 1 ;
  41. fibArray[ 1 ] = 1 ;
  42.  
  43. for ( int i = 2 ; i <= n ; i++ )
  44. fibArray [ i ] = ( fib ( n - 1 ) + ( fib ( n - 2 ) ) ) ;
  45.  
  46. }
  47.  
  48. return fibArray[ n ] ;
  49. }
I can't get it to work with numbers >=12; it gives a system error that it failed unexpectedly. I'm guessing it's a stack issue, but is there a way around it? Is my program the best it can be (using recursion and arrays)?
Last edited by Duki; Oct 25th, 2007 at 1:44 am.
It is practically impossible to teach good programming style to students that have had prior exposure to Basic; as potential programmers they are mentally mutilated beyond hope of regeneration.

-Edsger Dijkstra
Reply With Quote