-
Notifications
You must be signed in to change notification settings - Fork 17
/
Fibonacci.java
43 lines (35 loc) · 1.12 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
package by.andd3dfx.numeric;
import java.util.HashMap;
import java.util.Map;
/**
* Check <a href="https://habr.com/ru/post/423939/">this article</a>
* for comparison of top-down / down-top approaches:
*
* @see <a href="https://youtu.be/S5rfbd8JkWw">Video solution</a>
*/
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);
}
}