Advertisement
tien_noob

nth Fibo number - MulMatrix

Apr 11th, 2022
898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. //Make CSP great again
  2. //Vengeance
  3. #include <bits/stdc++.h>
  4. #define TASK "TESTCODE"
  5. #define Log2(x) 31 - __builtin_clz(x)
  6. using namespace std;
  7. const int mod = 1e9 + 7;
  8. long long n;
  9. struct Matrix
  10. {
  11.     vector<vector<int> > a;
  12.     int row() const
  13.     {
  14.         return a.size();
  15.     }
  16.     int col() const
  17.     {
  18.         return a[0].size();
  19.     }
  20.     auto & operator [] (int i)
  21.     {
  22.         return a[i];
  23.     }
  24.     const auto & operator[] (int i) const
  25.     {
  26.         return a[i];
  27.     }
  28.     Matrix(vector<vector<int> > b)
  29.     {
  30.         a = b;
  31.     }
  32.     Matrix(int r, int c)
  33.     {
  34.         a.resize(r);
  35.         for (int i = 0; i < r; ++ i)
  36.         {
  37.             a[i].resize(c, 0);
  38.         }
  39.     }
  40.     Matrix operator * (const Matrix &v)
  41.     {
  42.         Matrix u = *this;
  43.         Matrix x(u.row(), v.col());
  44.         for (int k = 0; k < u.col(); ++ k)
  45.         {
  46.             for (int i = 0; i < u.row(); ++ i)
  47.             {
  48.                 for (int j = 0; j < v.col(); ++ j)
  49.                 {
  50.                     x[i][j] = (x[i][j] + 1LL * u[i][k] * v[k][j]) % mod;
  51.                 }
  52.             }
  53.         }
  54.         return x;
  55.     }
  56. };
  57. void read()
  58. {
  59.     cin >> n;
  60. }
  61. void solve()
  62. {
  63.     Matrix a({
  64.         {0, 1},
  65.         {1, 1}
  66.     });
  67.     Matrix b({
  68.         {0, 1}
  69.     });
  70.     while(n > 0)
  71.     {
  72.         if (n & 1)
  73.         {
  74.             b = b * a;
  75.         }
  76.         a = a * a;
  77.         n >>= 1;
  78.     }
  79.     cout << b[0][0];
  80. }
  81. int main()
  82. {
  83.     ios_base::sync_with_stdio(false);
  84.     cin.tie(nullptr);
  85.     if (fopen(TASK".INP", "r"))
  86.     {
  87.         freopen(TASK".INP", "r", stdin);
  88.         //freopen(TASK".OUT", "w", stdout);
  89.     }
  90.     int t = 1;
  91.     bool typetest = false;
  92.     if (typetest)
  93.     {
  94.         cin >> t;
  95.     }
  96.     for (int __ = 1; __ <= t; ++ __)
  97.     {
  98.         //cout << "Case " << __ << ": ";
  99.         read();
  100.         solve();
  101.     }
  102. }
  103.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement