Advertisement
bero_0401

Fibonacci in log(N)

Jul 11th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define REP(i,n) for(int i = 0; i < (n); i++)
  4. const long long  mod = 1e9 + 7;
  5. struct Matrix {
  6.     int a[2][2] = {{0,0},{0,0}};
  7.     Matrix operator *(const Matrix& other) {
  8.         Matrix product;
  9.         REP(i,2)REP(j,2)REP(k,2) {
  10.                     product.a[i][k] = (product.a[i][k] + (long long) a[i][j] * other.a[j][k]) % mod;
  11.                 }
  12.         return product;
  13.     }
  14. };
  15. Matrix expo_power(Matrix a, long long k) {
  16.     Matrix product;
  17.     REP(i,2) product.a[i][i] = 1;
  18.     while(k > 0) {
  19.         if(k % 2) {
  20.             product = product * a;
  21.         }
  22.         a = a * a;
  23.         k /= 2;
  24.     }
  25.     return product;
  26. }
  27. int main() {
  28.     long long n;
  29.     cin >> n;
  30.     Matrix single;
  31.     single.a[0][0] = 0;
  32.     single.a[0][1] = 1;
  33.     single.a[1][0] = 1;
  34.     single.a[1][1] = 1;
  35.     Matrix total = expo_power(single, n);
  36.     cout << total.a[1][0] << endl;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement