-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfib-4.cc
More file actions
39 lines (32 loc) · 891 Bytes
/
fib-4.cc
File metadata and controls
39 lines (32 loc) · 891 Bytes
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
class Solution {
public:
int fib(int N) {
if (N <= 1) {
return N;
}
vector<vector<int>> A={{1, 1}, {1, 0}};
matrixPower(A, N-1);
return A[0][0];
}
void matrixPower(vector<vector<int>>& A, int N) {
if (N <= 1) {
return;
}
matrixPower(A, N/2);
multiply(A, A);
vector<vector<int>> B={{1, 1}, {1, 0}};
if (N%2 != 0) {
multiply(A, B);
}
}
void multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
int x = A[0][0] * B[0][0] + A[0][1] * B[1][0];
int y = A[0][0] * B[0][1] + A[0][1] * B[1][1];
int z = A[1][0] * B[0][0] + A[1][1] * B[1][0];
int w = A[1][0] * B[0][1] + A[1][1] * B[1][1];
A[0][0] = x;
A[0][1] = y;
A[1][0] = z;
A[1][1] = w;
}
};