-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacci.java
64 lines (62 loc) · 1.34 KB
/
Fibonacci.java
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
package codingProblems;
public class Fibonacci
{
public static void main(String args[])
{
int n=15;
System.out.println("Recursive:"+fiboRecursive(n));
System.out.println("DP:"+fiboDP(n));
System.out.println("DP:"+fiboMatrix(n));
}
//Recursive Fibo with exponential complexity
public static int fiboRecursive(int n)
{
if(n<=1)
return n;
return fiboRecursive(n-1)+fiboRecursive(n-2);
}
//Dynamic Programming with complexity O(n)
//space complexity can be reduced storing only last 2 elements
public static int fiboDP(int n)
{
int[] fibo=new int[n+1];
fibo[0]=0;
fibo[1]=1;
for(int i=2;i<=n;i++)
{
fibo[i]=fibo[i-1]+fibo[i-2];
}
return fibo[n];
}
//Using power of the matrix {{1,1},{1,0}} - optimized method
//Complexity O(log n)
public static int fiboMatrix(int n)
{
int[][] F={{1,1},{1,0}};
if(n==0)
return 0;
power(F,n-1);
return F[0][0];
}
static void power(int[][]F, int n)
{
if(n==0 || n==1)
return;
int[][] M={{1,1},{1,0}};
power(F,n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
static void multiply(int[][]F,int[][]M)
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
}