Data Structures and Algorithms
A function f(x, y) is defined as “if y is 0, return x; otherwise return f(y, x mod y)”. When f(84, 36) is called, what is the return value, and how many times is f called, including the first call?
- AReturns 12; called 3 times
- BReturns 12; called 4 times
- CReturns 6; called 3 times
Show answer and explanation
Answer: A. Returns 12; called 3 times
f(84, 36) calls f(36, 12) because 84 mod 36 = 12; that calls f(12, 0) because 36 mod 12 = 0; and since y is 0, it returns 12. The calls are f(84, 36), f(36, 12) and f(12, 0), three in total, and this is the Euclidean algorithm for the greatest common divisor. Because the function returns the result of its recursive call directly (tail recursion), a compiler that performs tail call optimization can turn it into a loop, so it does not keep using stack space however deep the recursion goes.
- A. Correct. f(84, 36) → f(36, 12) → f(12, 0), three calls, returning 12, the greatest common divisor of 84 and 36.
- B. The recursion ends at f(12, 0), when y becomes 0, so there is no fourth call.
- C. The greatest common divisor of 84 and 36 is 12 (84 = 12 × 7, 36 = 12 × 3).