Advertisement
bartekltg

fib 2

Feb 27th, 2024 (edited)
820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <boost/multiprecision/gmp.hpp>
  4. using namespace std;
  5.  
  6. typedef boost::multiprecision::mpz_int bint;
  7.  
  8. class timer{
  9.     std::chrono::time_point<std::chrono::high_resolution_clock> a,b;
  10. public:
  11.     void start(){a = std::chrono::high_resolution_clock::now();}
  12.     void stop() {b = std::chrono::high_resolution_clock::now();}
  13.     double value()
  14.     {
  15.         std::chrono::duration<double> elapsed_seconds = b-a;
  16.         return elapsed_seconds.count();
  17.     }
  18. };
  19.  
  20.  
  21. bint fib (uint64_t n){
  22.     if (n==0) return 0;
  23.     int shift =0;
  24.     uint64_t nn=n;
  25.     while (nn>1){
  26.         shift++;
  27.         nn/=2;
  28.     }
  29.  
  30.  
  31.     bint fk(1), fkp1(1); //F(k) and F(k+1) where k = n>>shift
  32.     bint f2kp1, f2k;
  33.  
  34.     for (;shift>0; shift--){
  35.         f2kp1 = (fkp1*fkp1+fk*fk);
  36.         f2k = (2*fkp1*fk-fk*fk);
  37.         if ((n>>(shift-1))%2==0 ){
  38.             fk = f2k;
  39.             fkp1 = f2kp1;
  40.         }else{
  41.             fk = f2kp1;
  42.             fkp1 = f2kp1+f2k;
  43.         }
  44.     }
  45.     return fk;
  46. }
  47.  
  48. void test (uint64_t j){
  49.  
  50.     timer t,t2;
  51.     t.start();
  52.     auto f = fib(j);
  53.     t.stop();t2.start();
  54.     string s = f.str();
  55.     t2.stop();
  56.     cout<<"fib("<< j<< ") " << s <<" number of digits: " <<s.length()<<endl;
  57.     cout <<"calcualted in "<< t.value() <<" s + string created in "<<t2.value() << endl;
  58. }
  59.  
  60. int main()
  61. {
  62.   test(30000000);
  63.  
  64.   return 0;
  65. }
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement