Skip to content

Commit 7361cfb

Browse files
Matrices
Matrix Addition. Matrix Multiplication. Recursive Matrix Exponentiation. Iterative Matrix Exponentiation.
1 parent c098bc2 commit 7361cfb

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Matrices.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <cstdio>
2+
#include <iostream>
3+
#include <vector>
4+
5+
using namespace std;
6+
7+
typedef long long ll;
8+
9+
#define row vector<ll>
10+
#define matrix vector<row>
11+
#define ROWS(v) (v).size()
12+
#define COLS(v) (v)[0].size()
13+
14+
const int N = 5e4+5, OO = 0x3f3f3f3f, MOD = 1e9+7;
15+
16+
inline ll fixMod(ll a, ll m){
17+
return (a%m+m)%m;
18+
}
19+
20+
void printMatrix(const matrix& m){
21+
for(auto r : m){
22+
for(auto x : r){
23+
cout << x << " ";
24+
}
25+
cout << endl;
26+
}
27+
}
28+
29+
matrix identity(int n){
30+
matrix ret(n ,row(n, 0));
31+
for(int i = 0 ; i < n ; ++i) ret[i][i] = 1;
32+
return ret;
33+
}
34+
35+
matrix add(const matrix& a, const matrix& b){
36+
matrix ret(ROWS(a), row(COLS(a), 0));
37+
for(int i = 0 ; i < ROWS(a) ; ++i)
38+
for(int j = 0 ; i < COLS(a) ; ++j)
39+
ret[i][j] = a[i][j] + b[i][j];
40+
return ret;
41+
}
42+
43+
matrix multiply(const matrix& a, const matrix& b){
44+
matrix ret(ROWS(a), row(COLS(b), 0));
45+
for(int r = 0 ; r < ROWS(a) ; ++r)
46+
for(int k = 0 ; k < COLS(a) ; ++k)
47+
if(a[r][k])for(int c = 0 ; c < COLS(b) ; ++c)
48+
ret[r][c] = (ret[r][c] + (a[r][k]*b[k][c])%MOD)%MOD;
49+
return ret;
50+
}
51+
52+
matrix power(const matrix& a, ll p){
53+
if(!p) return identity(ROWS(a));
54+
matrix m = power(a, p>>1);
55+
m = multiply(m, m);
56+
if(p&1) m = multiply(m, a);
57+
return m;
58+
}
59+
60+
matrix powerI(const matrix& a, ll p){
61+
matrix ret = identity(ROWS(a)), t = a;
62+
while(p){
63+
if(p&1) ret = multiply(ret, t);
64+
t = multiply(t, t);
65+
p >>= 1;
66+
}
67+
return ret;
68+
}
69+
70+
int main(){
71+
72+
return 0;
73+
}

0 commit comments

Comments
 (0)