Skip to content

Commit 786a660

Browse files
committed
Add Matrix Power code
1 parent 97623e9 commit 786a660

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Math/Matrix_Power/matrix_power.cpp

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
const int MaxSize = 2; //It depends on the problem (2 for computing Fibonacci series)
5+
const int mod = 1e9+7; //It depends on the problem as you may don't need it
6+
7+
struct Matrix{
8+
long long mat[MaxSize][MaxSize];
9+
};
10+
11+
Matrix matMul(Matrix a , Matrix b)
12+
{
13+
Matrix ans; int k;
14+
for(int i = 0 ; i < MaxSize ; i++)
15+
for(int j = 0 ; j < MaxSize ; j++){
16+
for(ans.mat[i][j] = k = 0 ; k < MaxSize ; k++){
17+
long long sum = (a.mat[i][k] * b.mat[k][j]) % mod;
18+
ans.mat[i][j] = (ans.mat[i][j] + sum) % mod;
19+
}
20+
}
21+
return ans;
22+
}
23+
24+
Matrix Identity(){
25+
Matrix res;
26+
for(int i = 0 ; i < MaxSize ; i++)
27+
for(int j = 0 ; j < MaxSize ; j++)
28+
res.mat[i][j] = (i == j);
29+
return res;
30+
}
31+
Matrix Power(Matrix base, long long pw)
32+
{
33+
Matrix ans = Identity();
34+
while(pw){
35+
if(pw & 1) ans = matMul(ans , base);
36+
base = matMul(base, base);
37+
pw >>= 1;
38+
}
39+
return ans;
40+
}
41+
42+
int main(){
43+
44+
// Matrix Power is a technique not a specific problem
45+
// So I wrote just the template of its code.
46+
47+
48+
return 0;
49+
}

0 commit comments

Comments
 (0)