forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci.java
More file actions
41 lines (33 loc) · 1.03 KB
/
Copy pathFibonacci.java
File metadata and controls
41 lines (33 loc) · 1.03 KB
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
package by.andd3dfx.numeric;
import java.util.HashMap;
import java.util.Map;
/**
* Check this article for comparison of top-down / down-top approaches:
* https://habr.com/ru/post/423939/
*/
public class Fibonacci {
private static final Map<Integer, Integer> map = new HashMap<>() {{
put(0, 0);
put(1, 1);
}};
/**
* Top-down approach (recursive, better)
*/
public static int calculate(int n) {
if (n < 0) throw new IllegalArgumentException("Number should be not less than 0!");
if (!map.containsKey(n)) {
map.put(n, calculate(n - 1) + calculate(n - 2));
}
return map.get(n);
}
/**
* Down-top approach (loop, just as example)
*/
public static int calculate2(int n) {
if (n < 0) throw new IllegalArgumentException("Number should be not less than 0!");
for (int i = 2; i <= n; i++) {
map.put(n, map.get(n - 1) + map.get(n - 2));
}
return map.get(n);
}
}