alfps

Fibonacci series directly via formula

Dec 4th, 2020
1,130
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <kickstart/all.hpp>        // Available at GitHub.
  2. using namespace kickstart::all;
  3.  
  4. #include <math.h>       // pow, llround
  5. #include <fenv.h>       // fetestexcept, FE_INVALID, feclearexcept, FE_ALL_EXCEPT
  6.  
  7. auto to_longlong( const double value )
  8.     -> long long
  9. {
  10.     const long long result = ::llround( value );
  11.     if( ::fetestexcept( FE_INVALID ) ) {
  12.         ::feclearexcept( FE_ALL_EXCEPT );
  13.         KS_FAIL_( range_error, ""s << value << " exceeds the range of `long long`." );
  14.     }
  15.     return result;
  16. }
  17.  
  18. void cpp_main( const string_view& cmd_verb, const vector<string_view>& args )
  19. {
  20.     hopefully( args.size() == 1 )
  21.         or exit_app_with_message( ""s << "Usage: " << cmd_verb << " NUMBER" );
  22.  
  23.     const int       n           = to_int( args[0] );
  24.     const double    sqrt_5      = sqrt( 5 );
  25.     const double    phi_plus    = (1 + sqrt_5)/2;
  26.     const double    phi_minus   = (1 - sqrt_5)/2;
  27.     const double    fib_n_float = (pow( phi_plus, n ) - pow( phi_minus, n))/sqrt_5;
  28.     const long long fib_n       = to_longlong( fib_n_float );
  29.  
  30.     out << fib_n << endl;
  31. }
  32.  
  33. auto main( int n_cmd_parts, char* cmd_parts[] )
  34.     -> int
  35. { return with_exceptions_displayed( cpp_main, n_cmd_parts, cmd_parts ); }
  36.  
RAW Paste Data