Fibonacci.java 874 B

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