forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FibonacciMatrixMethod.java
63 lines (52 loc) · 1.69 KB
/
FibonacciMatrixMethod.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
/**
* Java program to find the nth Fibonacci number in O(log n) time
* complexity.
*
* Algorithm:
* Consider a matrix:
* | 1 1 | | 1 1 |
* | 1 0 | | 1 0 |
* The nth power of the matrix is:
* | F(n + 1) F(n) |
* | F(n) F(n - 1) |
* where F(n) is the nth Fibonacci number
*
* Time Complexity: O(log n)
* Extra Space Complexity: O(log n) for recursive stack calls
*/
class FibonacciMatrixMethod {
public static void main(String args[]) {
int n = 8;
System.out.print(n + "th Fibonacci number is ");
System.out.println(getFibonacci(n));
}
// method to get the nth Fibonacci number
static int getFibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int f[][] = { {1, 1}, {1, 0} };
// get f^(n - 1) whose 1st element is F(n)
getMatrixPower(f, n - 1);
return f[0][0];
}
// returns f in nth power
static void getMatrixPower(int f[][], int n) {
if (n == 0 || n == 1) return;
// gets f^(n / 2)
getMatrixPower(f, n / 2);
multiplyMatrix(f, f); // squaring the matrix
int m[][] = { {1, 1}, {1, 0} };
// if n was odd multiply once with initial matrix
if (n % 2 != 0)
multiplyMatrix(f, m);
}
// multiplies matrices f and m, result stored in f
static void multiplyMatrix(int f[][], int m[][]) {
int a = f[0][0] * m[0][0] + f[0][1] * m[1][0];
int b = f[0][0] * m[0][1] + f[0][1] * m[1][1];
int c = f[1][0] * m[0][0] + f[1][1] * m[1][0];
int d = f[1][0] * m[0][1] + f[1][1] * m[1][1];
f[0][0] = a; f[0][1] = b;
f[1][0] = c; f[1][1] = d;
}
}