Advertisement
Jasir

Matrix Exponentiation

Aug 14th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. ///M*Fn = Fn+1
  2. struct Matrix {
  3.     const static int N = 3;
  4.     int n;
  5.     int v[N][N];
  6.  
  7.     void init(int _n) {
  8.         n = _n;
  9.         for(int i=0;i<n;i++){
  10.             for(int j=0;j<n;j++){
  11.                 v[i][j] = 0;
  12.             }
  13.         }
  14.     }
  15.     void ident() {
  16.         for(int i=0;i<n;i++){
  17.             for(int j=0;j<n;j++){
  18.                 v[i][j] = 0;
  19.             }
  20.         }
  21.         for(int i=0;i<n;i++){
  22.             v[i][i] = 1;
  23.         }
  24.     }
  25.  
  26.     Matrix operator+(const Matrix &o) const {
  27.         assert(n == o.n);
  28.  
  29.         Matrix res; res.init(n);
  30.         for(int i=0;i<n;i++){
  31.             for(int j=0;j<n;j++){
  32.                 res.v[i][j] = v[i][j] + o.v[i][j];
  33.                 if (res.v[i][j] >= mod) res.v[i][j] -= mod;
  34.             }
  35.         }
  36.         return res;
  37.     }
  38.  
  39.     Matrix operator*(const Matrix &o) const {
  40.         assert(n == o.n);
  41.         Matrix res; res.init(n);
  42.         for(int i=0;i<n;i++){
  43.             for(int j=0;j<n;j++){
  44.                 for(int k=0;k<n;k++){
  45.                     res.v[i][j] = (v[i][k] * o.v[k][j] + res.v[i][j])%mod;
  46.                 }
  47.             }
  48.         }
  49.         return res;
  50.     }
  51.  
  52.     Matrix operator^(long long k) {
  53.         Matrix res; res.init(n); res.ident();
  54.         Matrix a = *this;
  55.         while (k) {
  56.             if (k&1LL) res = res*a;
  57.             a = a*a;
  58.             k /= 2;
  59.         }
  60.         return res;
  61.     }
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement