Question 1Multiple choiceRecursion & recursive tracing
Consider the Python function
def f(n):
if n < 2:
return 1
return f(n - 1) + 2 * f(n - 2)
What value does f(5) return?
- A.
21
- B.
11
- C.
8
- D.
43
Worked solution
Trace upward from the base cases rather than expanding the whole call tree. The base case covers and , both returning 1.
Check with the closed form: the recurrence has characteristic equation , so . The base cases give and , so and , and .
Option B (11) is the most tempting error: it is , the result of stopping one level early, and it is also what you get by wrongly taking . Option C (8) is the plain Fibonacci value obtained by dropping the factor of 2. Option D (43) is , one level too far.
Note that the call count grows quickly: makes 15 calls in total, because every call with spawns two more, which is why memoization matters for recurrences like this one.
f(5) = 21 (option A).