Bifalgorithm post · Computer science one · Recursion
How can Fibonacci numbers be computed recursively in Java?
How can Fibonacci numbers be computed recursively in Java? (Computer science one · Recursion) — "As another example, consider the following Java implementation…
Ideas in this flowchart
- Java Fibonacci implementations: naive recursion and explicit memoization
- For n < 0, both implementations throw an IllegalArgumentException.
- For n <= 1, both implementations return 1.
- Naive recursive Fibonacci implementation
- For n > 1, it recursively computes fibonacci(n-1) + fibonacci(n-2).
- Memoized Fibonacci implementation
- Java provides no implicit memoization, so computed values must be stored explicitly.
- A Map<Integer, Integer> stores previously computed Fibonacci values.
- The implementation checks whether the value for n is already in the map.
- If the value is absent, it recursively computes the two preceding values, sums them, and stores the result.
- If the value is present, the stored result is returned directly.