-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmatrix_exponentiation.cpp
62 lines (62 loc) · 1.76 KB
/
matrix_exponentiation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
struct Matrix{
int matrixSize;
vector< vector < int64_t > >mat;
Matrix(const int &r){
matrixSize = r;
mat.assign(r , vector<int64_t>(r, 0));
}
Matrix operator*(const Matrix &B){
Matrix T(matrixSize);
for ( int i = 0 ; i < matrixSize; ++i) {
for ( int j = 0 ; j < matrixSize; ++j) {
for ( int k = 0 ; k < matrixSize; ++k) {
T.mat[i][j] += (mat[i][k] * B.mat[k][j]) % MOD;
T.mat[i][j] %= MOD;
}
}
}
return T;
}
void operator*=(const Matrix &B){
Matrix T(matrixSize);
for ( int i = 0 ; i < matrixSize; ++i) {
for ( int j = 0 ; j < matrixSize; ++j) {
for ( int k = 0 ; k < matrixSize; ++k) {
T.mat[i][j] += (mat[i][k] * B.mat[k][j]) % MOD;
T.mat[i][j] %= MOD;
}
}
}
for (int i = 0; i < matrixSize; ++i){
for ( int j = 0; j < matrixSize; ++j ) {
mat[i][j] = T.mat[i][j];
}
}
}
void makeIdentity(){
for ( int i = 0; i < matrixSize; ++i ) {
mat[i][i] = 1;
}
}
friend Matrix power(Matrix &A , int64_t b){
Matrix temp(A.matrixSize);
temp.makeIdentity();
while(b){
if(b&1){
temp = temp*A;
}
b>>=1;
A = A*A;
}
return temp;
}
friend ostream& operator<<(ostream&cout, const Matrix &a) {
for(int i=0; i < a.matrixSize; ++i) {
for ( int j = 0; j < a.matrixSize; ++j ) {
cout << a.mat[i][j] <<' ';
}
cout << '\n';
}
return cout;
}
};