Concept
How can Fibonacci numbers be computed recursively in Java?
ComputerScienceOne / Recursion
"As another example, consider the following Java implementation of the naive recursive Fibonacci sequence. An additional condition has been included to check for “invalid” negative values of n for which an exception is thrown.\n\n1 public static int fibonacci(int n) {\n\n2 if(n < 0) {\n\n3 throw new IllegalArgumentException(\"Undefined for n < 0\");\n\n4 } else if(n <= 1) {\n\n5 return 1;\n\n6 } else {\n\n7 return fibonacci(n-1) + fibonacci(n-2);\n\n8 }\n\n9 }\n\nJava is not a language that provides implicit memoization. Instead, we need to explicitly keep track of values using a table. In the following example, we use a Map data structure to store previously computed values.\n\n1 public static int fibMemoization(int n, Map<Integer, Integer> m) {\n\n2 if(n < 0) {\n\n3 throw new IllegalArgumentException(\"Undefined for n < 0\");\n\n4 } else if(n <= 1) {\n\n5 return 1;\n\n6 } else {\n\n7 Integer result = m.get(n);\n\n8 if(result == null) {\n\n9 Integer a = fibMemoization(n-1, m);\n\n10 Integer b = fibMemoization(n-2, m);\n\n11 result = a + b;\n\n12 m.put(n, result);\n\n13 }\n\n14 return result;\n\n15 }\n\n16 }"
Related Ideas
- How is memoization implemented for recursive Fibonacci in C?ComputerScienceOne · Recursion
- How can recursion be made tail-recursive in C?ComputerScienceOne · Recursion
- How is recursion implemented in Java?ComputerScienceOne · Recursion
- How can recursive functions be written in C?ComputerScienceOne · Recursion
- What happens when a function calls itself?ComputerScienceOne · Recursion
- How can a countdown be written without a loop?ComputerScienceOne · Recursion
- How does Java handle arithmetic with wrapper classes?ComputerScienceOne · Operators
- How do recursive Fibonacci functions work with memoization?ComputerScienceOne · Scaling a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .