C++矩阵类(乘法与快速幂)

2019-04-14 12:55发布

class matrix { public: int r; int c; vector<vector<int> >m; matrix(int _r, int _c): c(_c), r(_r) { m.resize(r); for(int i=0;ioperator *(const matrix& ob) { matrix m(r, ob.c); for (int i = 0; i < r; i++) for (int j = 0; j < ob.c; j++) { m.m[i][j] = 0; for (int k = 0; k < c; k++) m.m[i][j] += this->m[i][k] * ob.m[k][j]; } return m; } matrix operator +(const matrix& ob) { matrix m(r, c); for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) m.m[i][j]=this->m[i][j]+ob.m[i][j]; return m; } void unit() { for (int i = 0; i < r; i++) { for(int j=0;j0; m[i][i] = 1; } return; } matrix operator ^(int n) { matrix ans(r, c); matrix m(r,c); m = (*this); ans.unit(); while (n) { if (n & 1) ans = ans * m; m = m * m; n >>= 1; } return ans; } void display() { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) printf("%10lld", m[i][j]); cout << endl; } } };