forked from arnab2001/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Determining fibonacci series in Log(n) time
67 lines (55 loc) · 1.35 KB
/
Determining fibonacci series in Log(n) time
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
// question link - https://practice.geeksforgeeks.org/problems/cows-of-fooland5818/1#
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
void multiply(long long int mat[2][2],long long int m[2][2]){
long long int temp[2][2];
long long int x = 1000000007;
temp[0][0]=mat[0][0]*m[0][0]+mat[0][1]*m[1][0];
temp[0][1]= mat[0][0]*m[0][1]+mat[0][1]*m[1][1];
temp[1][0]= mat[1][0]*m[0][0]+mat[1][1]*m[1][0];
temp[1][1]= mat[1][0]*m[0][1]+mat[1][1]*m[1][1];
mat[0][0]=temp[0][0]%x;
mat[0][1]=temp[0][1]%x;
mat[1][0]=temp[1][0]%x;
mat[1][1]=temp[1][1]%x;
}
void mat_power(long long int mat[2][2],long long int n){
if(n==1) return; // n==0 will never come
mat_power(mat,n/2);
multiply(mat,mat);
long long int m[2][2]={
{1,1},
{1,0}
};
if(n%2!=0)
multiply(mat,m);
}
////////////////////////////////////////////*
int TotalAnimal(long long int n){
long long int mat[2][2]={
{1,1},
{1,0}
};
if(n==0) return 1;
mat_power(mat,n+1);
return mat[0][1];
// Code here
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
long long int N;
cin >> N;
Solution ob;
int ans = ob.TotalAnimal(N);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends