Question 15
Back to Exercise
What is the output of the following Java program?
import java.util.HashMap;
import java.util.Map;
public class Main {
private static final Map<Integer, Long> CACHE = new HashMap<>();
static int computed = 0;
static long fib(int n) {
if (n < 2) return n;
Long c = CACHE.get(n);
if (c != null) return c;
computed++;
long v = fib(n - 1) + fib(n - 2);
CACHE.put(n, v);
return v;
}
public static void main(String[] args) {
long a = fib(30);
int afterFirst = computed;
long b = fib(35);
System.out.println(a + " " + afterFirst + " " + b + " " + computed);
}
}
- A 832040 29 9227465 34 Correct
- B 832040 30 9227465 35
- C 832040 29 9227465 63
- D 832040 1 9227465 2
Correct Answer: Option A
Values 2..30 are computed once (29). The static cache survives between calls, so fib(35) computes only 31..35 (5 more).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!