Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
import java.util.HashMap;
2
import java.util.Map;
3
4
public class Fibonacci {
5
private final Map<Integer, Integer> functionValues;
6
7
public Fibonacci() {
8
functionValues = new HashMap<Integer, Integer>();
9
functionValues.put(0, 0);
10
functionValues.put(1, 1);
11
}
12
13
private int calculate(int x) {
14
return getFunctionValue(x - 1) + getFunctionValue(x - 2);
15
}
16
17
public int getFunctionValue(int x) {
18
if (x < 0) {
19
/* Exception werfen */
20
throw new IllegalArgumentException(
21
"Fibonacci is not defined for negative values");
22
}
23
24
if (functionValues.containsKey(x)) {
25
return functionValues.get(x);
26
} else {
27
int functionValue = calculate(x);
28
functionValues.put(x, functionValue);
29
return functionValue;
30
}
31
}
32
}
33
34