-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix Exponentiation .cpp
More file actions
72 lines (53 loc) · 1.58 KB
/
Matrix Exponentiation .cpp
File metadata and controls
72 lines (53 loc) · 1.58 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
70
71
72
// Finding the n-th term of a linear recurrance relation in logn time
vector<vector<int>>Multiply (vector<vector<int>> &one , vector<vector<int>> &two) //pass them as reference to save time
{
vector<vector<int>>res;
int D = one.size();
for(int i=0;i<D;i++)
{
vector<int>temp;
for(int j=0;j<D;j++)
{
int cnt = 0;
for(int k=0;k<D;k++)
{
cnt += one[i][k]*two[k][j];
}
temp.push_back(cnt);
}
res.push_back(temp);
}
return res;
}
vector<vector<int>> Mat_Ex(vector<vector<int>> Mat , int b) //don't pass Mat as reference
{
vector<vector<int>> ans
{
{1,0},
{0,1}
}; //Identity Matrix {Adjust its dimension according to Mat
while(b>0)
{
if(b&1)
{
ans = Multiply(ans,Mat);
}
Mat = Multiply(Mat,Mat);
b>>=1;
}
return ans;
}
int32_t main()
{
ios::sync_with_stdio(0);
cin.tie(0);
// For finding nth fibbonacci
vector<vector<int>>Mat{
{1,1},
{1,0}
};
int n;
cin>>n; //n>2
cout<<Mat_Ex(Mat , n-2)[0][0]<<endl;
return 0;
}