Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f680c87

Browse files
committed
added fibonacci number calculation in o(log(n))
1 parent 435ebc9 commit f680c87

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
-12.9 KB
Binary file not shown.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
typedef long long ll;
5+
const int S = 2;
6+
const int MOD = 1000000000+7;
7+
const int MODQ = 1000000000+7-1;
8+
9+
struct mat_t {
10+
int m[S][S];
11+
};
12+
13+
// Function to calculate matrix multiplication
14+
mat_t mat_mult(mat_t& a, mat_t& b) {
15+
mat_t c;
16+
17+
for(int i=0; i<S; i++)
18+
for(int j=0; j<S; j++)
19+
c.m[i][j] = 0;
20+
21+
for(int i=0; i<S; i++) {
22+
for(int k=0; k<S; k++) {
23+
for(int j=0; j<S; j++) {
24+
c.m[i][j] = (c.m[i][j]+ ll(a.m[i][k])*b.m[k][j] % MODQ) % MODQ;
25+
}
26+
}
27+
}
28+
29+
return c;
30+
}
31+
32+
33+
// Calculation Matrix Power in O(log(n)) ie A^n(where A is matrix)
34+
// same as exponentiation power
35+
mat_t mat_pow(mat_t a, int n) {
36+
mat_t w;
37+
38+
for(int i=0; i<S; i++) {
39+
for(int j=0; j<S; j++)
40+
w.m[i][j] = i==j;
41+
}
42+
43+
44+
while(n) {
45+
if(n&1) w = mat_mult(w, a);
46+
a = mat_mult(a, a);
47+
n/=2;
48+
}
49+
50+
return w;
51+
}
52+
53+
54+
int main() {
55+
int n; cin >> n;
56+
57+
58+
mat_t m;
59+
m.m[0][0] = m.m[0][1] = m.m[1][0] = 1;
60+
m.m[1][1] = 0;
61+
62+
m = mat_pow(m, n);
63+
cout << m.m[0][1] << endl;
64+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /