fork download
  1. /*
  2.   Fibonacci Numbers to the nth term, using the formula:
  3.  
  4.   (1 + sqrt(5))^n - (1 - sqrt(5))^n
  5.   F[n] = =================================
  6.   2^n * sqrt(5)
  7. */
  8.  
  9. #include <vector>
  10. #include <cmath>
  11. #include <iostream>
  12. #include <limits>
  13. #include <iomanip>
  14.  
  15. static std::vector<double> fibonacci_sequence( unsigned int n )
  16. {
  17. static const double root5 = std::sqrt(5.0) ;
  18. static const double root5_plus_1 = root5 + 1 ;
  19. static const double root5_minus_1 = root5 - 1 ;
  20.  
  21. std::vector<double> result { 1, 1 } ;
  22.  
  23. double a = root5_plus_1 * root5_plus_1 ;
  24. double b = root5_minus_1 * root5_minus_1 ;
  25. double denom = root5 * 4 ;
  26.  
  27. for( unsigned int i = 2 ; i < n ; ++i )
  28. {
  29. a *= root5_plus_1 ;
  30. b *= root5_minus_1 ;
  31. denom *= 2 ;
  32.  
  33. result.push_back( std::round( (a-b)/denom ) ) ;
  34. }
  35.  
  36. return result ;
  37. }
  38.  
  39. static unsigned int number_of_terms( unsigned int max, const char* prompt )
  40. {
  41. std::cout << "please enter " << prompt << ": [2, " << max << "]: " ;
  42. unsigned int n ;
  43. if( std::cin >> n && n >= 2 && n <= max ) return n ;
  44.  
  45. std::cin.clear() ;
  46. std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
  47. return number_of_terms( max, prompt ) ;
  48. }
  49.  
  50. static int ndigits( unsigned int n )
  51. {
  52. if( n < 10 ) return 1 ;
  53. else return 1 + ndigits( n/10 ) ;
  54. }
  55.  
  56. int main()
  57. {
  58. constexpr unsigned int MAX_TERMS = 50 ;
  59. const char* const prompt = "number of terms in the fibonacci_sequence" ;
  60.  
  61. const auto seq = fibonacci_sequence( number_of_terms( MAX_TERMS, prompt ) ) ;
  62.  
  63. std::cout << std::fixed << std::setprecision(0) << '\n' ;
  64. const int width = ndigits( seq.back() ) + 2 ;
  65.  
  66. int cols = 0 ;
  67. const int maxcols = 60 - width ;
  68. for( auto v : seq )
  69. {
  70. std::cout << std::setw(width) << v ;
  71. cols += width ;
  72. if( cols > maxcols ) { std::cout << '\n' ; cols = 0 ; }
  73. }
  74. std::cout << '\n' ;
  75. }
  76.  
Success #stdin #stdout 0s 3436KB
stdin
35
stdout
please enter number of terms in the fibonacci_sequence: [2, 50]: 
        1        1        2        3        5        8
       13       21       34       55       89      144
      233      377      610      987     1597     2584
     4181     6765    10946    17711    28657    46368
    75025   121393   196418   317811   514229   832040
  1346269  2178309  3524578  5702887  9227465