Skip to content

Commit 01c4eb7

Browse files
committed
fibonacci matrix DP
1 parent 60b4ca4 commit 01c4eb7

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package main.java.dp;
2+
3+
import java.util.Scanner;
4+
5+
public class Fibonacci {
6+
public static void main(String[] args) {
7+
final Scanner scanner = new Scanner(System.in);
8+
final int n = scanner.nextInt();
9+
//Fib sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
10+
System.out.println(fibonacciDP(n));
11+
System.out.println(fibonacciRecursive(n));
12+
System.out.println(fibonacciMatrix(n));
13+
}
14+
15+
private static long fibonacciRecursive(final int n) {
16+
if (n < 2) {
17+
if (n == 0) {
18+
return 0;
19+
} else {
20+
return 1;
21+
}
22+
}
23+
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
24+
}
25+
26+
private static long fibonacciDP(final int n) {
27+
if (n < 2) {
28+
if (n == 0) {
29+
return 0;
30+
} else {
31+
return 1;
32+
}
33+
}
34+
long first = 0, second = 1;
35+
for (int i = 0; i < n; i++) {
36+
final long temp = first;
37+
first = second;
38+
second = second + temp;
39+
}
40+
return first;
41+
}
42+
43+
private static long fibonacciMatrix(int n) {
44+
if (n < 2) {
45+
if (n == 0) {
46+
return 0;
47+
} else {
48+
return 1;
49+
}
50+
}
51+
n--;
52+
long product[][] = new long[][]{{1, 0}, {0, 1}}, M[][] = new long[][]{{1, 1}, {1, 0}};
53+
while (n > 0) {
54+
if ((n & 1) == 1) {
55+
product = matrixMult(product, M);
56+
}
57+
M = matrixMult(M, M);
58+
n = n >> 1;
59+
}
60+
return product[1][0] + product[1][1];
61+
}
62+
63+
private static long[][] matrixMult(final long[][] first, final long[][] second) {
64+
final long f00 = first[0][0] * second[0][0] + first[0][1] * second[1][0],
65+
f01 = first[0][0] * second[0][1] + first[0][1] * second[1][1],
66+
f10 = first[1][0] * second[0][0] + first[1][1] * second[1][0],
67+
f11 = first[1][0] * second[0][1] + first[1][1] * second[1][1];
68+
return new long[][]{{f00, f01}, {f10, f11}};
69+
}
70+
}

0 commit comments

Comments
 (0)