Matrix_code

math - Matrix Exponentiation

Jul 7th, 2017 (edited)
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. /*
  2.     Change MRows,MCols
  3.     1. Call init(row,col)
  4.     2. Build Initial Matrix
  5.     3. Expo
  6.  
  7. */
  8. const int MRows = 2;
  9. const int MCols = 2;
  10. typedef long long  m_t;
  11. long long MOD;
  12. struct Matrix {
  13.    
  14.     int r, c;
  15.     m_t m[MRows][MCols];
  16.    
  17.     void init(int R, int C) {
  18.         memset(m, 0, sizeof m);
  19.         r=R; c=C;
  20.     }
  21.     void iden() {
  22.         for(int i = 0 ; i < r; i ++) m[i][i] = 1;
  23.     }
  24.     void print() {
  25.        
  26.         puts("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  27.         for (int i = 0; i < r; ++i) {
  28.             for (int j = 0; j < c; ++j) printf("%4d  ", m[i][j]);
  29.             printf("\n");
  30.         }
  31.         puts("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  32.     }
  33.    
  34.     void mul(const Matrix &y, Matrix &z) const {
  35.         // value Stored in Z
  36.         z.r = r, z.c = y.c; m_t v;
  37.        
  38.         for (int i = 0; i < z.r; ++i)
  39.             for (int j = 0; j < z.c; ++j) {
  40.                 v = 0;
  41.                 for (int k = 0; k < c; ++k){
  42.                     v += m[i][k] * y.m[k][j];
  43.                     v %= MOD;
  44.                    
  45.                 }
  46.                
  47.                 z.m[i][j] = v;
  48.             }
  49.     }
  50.     void add(const Matrix &B , Matrix &c) {
  51.         c.r = c.c = r;
  52.         for(int i = 0 ; i < c.r ; i ++ ){
  53.             for(int j = 0 ; j <c.c ; j ++ ) {
  54.                 c.m[i][j] = m[i][j] + B.m[i][j];
  55.             }
  56.         }
  57.     }
  58.     void exp(long long e, Matrix &z) {
  59.         //value stored in Z
  60.         z.init(r, c); z.iden();
  61.         Matrix x, b = *this;
  62.         while (true) {
  63.             if (e & 1) { z.mul(b, x); z = x; }
  64.             e >>= 1;
  65.             if (e == 0) break;
  66.             b.mul(b, x);
  67.             b = x;
  68.         }
  69.     }
  70. };
Add Comment
Please, Sign In to add comment