-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixExponentiationAndStruct.cpp
More file actions
69 lines (65 loc) · 1.13 KB
/
Copy pathMatrixExponentiationAndStruct.cpp
File metadata and controls
69 lines (65 loc) · 1.13 KB
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
63
64
65
66
67
68
69
#define int ll
const int MOD = 1e9 + 7;
const int N = 10;
struct Matrix {
int arr[N][N];
// setting all the elements to 0
void reset() {
memset(arr,0,sizeof(arr));
}
// making matirx's diagonal one
void make_igen() {
memset(arr,0,sizeof(arr));
FOR(i,0,N) arr[i][i] = 1;
}
// adding the matrix
Matrix add(Matrix &a, Matrix &b) {
Matrix c;
c.reset();
FOR(i,0,N) {
FOR(j,0,N) {
c.arr[i][j] = a.arr[i][j] + b.arr[i][j];
}
}
return c;
}
// multiplying the matrix
Matrix mul(Matrix &a, Matrix &b) {
Matrix c;
FOR(i,0,N) {
FOR(j,0,N) {
int cur = 0;
FOR(k,0,N) {
int temp = a.arr[i][k] * b.arr[k][j];
temp %= MOD;
cur = (cur + temp);
if(cur >= MOD)
cur -= MOD;
}
c.arr[i][j] = cur;
}
}
return c;
}
// For Printing the Matrix
void Print(Matrix p) {
FOR(i,0,N) {
FOR(j,0,N) {
cout << p.arr[i][j] << " ";
}
cout << endl;
}
}
};
Matrix pow(Matrix a, int b) { // matrix exponentiation
Matrix res;
res.make_igen();
while(b) {
if(b%2) {
res = res.mul(res,a);
}
a = a.mul(a,a);
b /= 2;
}
return res;
}