-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNth_Number_Fibonacci_Sequence.cpp
61 lines (47 loc) · 1.03 KB
/
Nth_Number_Fibonacci_Sequence.cpp
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
#include <bits/stdc++.h>
using namespace std;
int mod = 1e9+7;
void multiply(long F[2][2], long M[2][2]);
void power(long F[2][2], int n);
int fibonacciNumber(int n)
{
long F[2][2] = {{1, 1}, {1, 0}};
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0]%mod;
}
void power(long F[2][2], int n)
{
if(n == 0 || n == 1)
return;
long M[2][2] = {{1, 1}, {1, 0}};
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
}
void multiply(long F[2][2], long M[2][2])
{
long x = (F[0][0] * M[0][0])%mod + (F[0][1] * M[1][0])%mod;
long y = (F[0][0] * M[0][1])%mod + (F[0][1] * M[1][1])%mod;
long z = (F[1][0] * M[0][0])%mod + (F[1][1] * M[1][0])%mod;
long w = (F[1][0] * M[0][1])%mod + (F[1][1] * M[1][1])%mod;
F[0][0] = x%mod;
F[0][1] = y%mod;
F[1][0] = z%mod;
F[1][1] = w%mod;
}
/*
Example:
Input=
10 <= The number of sequences into the Fibonacci Sequence
7
1
3
Output=
55 <= The "N"th Number in the Fibonacci Sequence
13
1
2
*/