Advertisement
srjchoubey2

Untitled

Feb 27th, 2022
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const unsigned long long mod_number = 1e9+7;
  5.  
  6. // Helper function that multiplies 2
  7. // matrices F and M of size 2*2, and
  8. // puts the multiplication result
  9. // back to F[][]
  10. void multiply(unsigned long long F[2][2], unsigned long long M[2][2]);
  11.  
  12. // Helper function that calculates F[][]
  13. // raise to the power n and puts the
  14. // result in F[][]
  15. // Note that this function is designed
  16. // only for fib() and won't work as
  17. // general power function
  18. void power(unsigned long long F[2][2], unsigned long long n);
  19.  
  20. unsigned long long fib(unsigned long long n)
  21. {
  22.     unsigned long long F[2][2] = { { 1, 1 }, { 1, 0 } };
  23.      
  24.     if (n == 0)
  25.         return 0;
  26.          
  27.     power(F, n - 1);
  28.      
  29.     return F[0][0] % mod_number;
  30. }
  31.  
  32. void multiply(unsigned long long F[2][2], unsigned long long M[2][2])
  33. {
  34.     unsigned long long x = F[0][0] * M[0][0]) +
  35.             F[0][1] * M[1][0];
  36.     unsigned long long y = F[0][0] * M[0][1] +
  37.             F[0][1] * M[1][1];
  38.     unsigned long long z = F[1][0] * M[0][0] +
  39.             F[1][1] * M[1][0];
  40.     unsigned long long w = F[1][0] * M[0][1] +
  41.             F[1][1] * M[1][1];
  42.      
  43.     F[0][0] = x % mod_number;
  44.     F[0][1] = y % mod_number;
  45.     F[1][0] = z % mod_number;
  46.     F[1][1] = w % mod_number;
  47. }
  48.  
  49. void power(unsigned long long F[2][2], unsigned long long n)
  50. {
  51.     unsigned long long i;
  52.     unsigned long long M[2][2] = { { 1, 1 }, { 1, 0 } };
  53.      
  54.     // n - 1 times multiply the
  55.     // matrix to {{1,0},{0,1}}
  56.     for(i = 2; i <= n; i++)
  57.         multiply(F, M);
  58. }
  59.  
  60. // Driver code
  61. int main()
  62. {
  63.     unsigned long long n = 75218624135794268;
  64.    
  65.     // cin >> n;
  66.      
  67.     cout <<  fib(n) << endl;
  68.      
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement