-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeneralised Fibonacci numbers
58 lines (52 loc) · 1.43 KB
/
Generalised Fibonacci numbers
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
class Solution {
static long mat[][], M[][];
static long m;
static long genFibNum(Long a, Long b, Long c, long n, long mod) {
// code here
// long g1=1, g2=1;
// if(n==1) return g1%m;
// if(n==2) return g2%m;
// long g3=0;
// for(long i=3; i<=n; i++) {
// g3 = (a * g2) + (b * g1) + c;
// g1 = g2;
// g2 = g3;
// }
// return g3 % m;
// Optimizes code Log(n) time complexity
m=mod;
mat=new long[][]{{a,b,1},{1,0,0},{0,0,1}};
M=new long[][]{{a,b,1},{1,0,0},{0,0,1}};
if(n<=2){
return 1%m;
}
else{
power(mat,n-2);
return (mat[0][0]+mat[0][1]+c*mat[0][2])%m;
}
}
static void multiply(long F[][], long M[][]){
long result[][]=new long[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
for(int k=0;k<3;k++){
result[i][j]+=(F[i][k]*M[k][j])%m;
result[i][j]%=m;
}
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
F[i][j]=result[i][j];
}
}
}
static void power(long F[][], long n){
if(n==0 || n==1)
return;
power(F, n/2);
multiply(F,F);
if(n%2!=0)
multiply(F,M);
}
};