Consider the following recursive Java function 𝑓 that takes two long…
2020
Consider the following recursive Java function 𝑓 that takes two long arguments and returns a float value:
public static float f (long m, long n) {
float result = (float)m / (float)n;
if (m < 0 || n<0) return 0.0f;
else result -=f(m*2, n*3);
return result;
}
Which of the following real values best approximates the value of 𝑓(1,3)?
- A.
0.2
- B.
0.4
- C.
0.6
- D.
0.8
Attempted by 77 students.
Show answer & explanation
Correct answer: A
Key idea: write the recurrence and recognize an alternating geometric series.
From the code, for nonnegative m and n we have f(m,n) = m/n - f(2m,3n).
Apply this to f(1,3):
f(1,3) = 1/3 - f(2,9) = 1/3 - (2/9 - f(4,27)) = 1/3 - 2/9 + 4/27 - ...
This is an infinite alternating geometric series with first term a = 1/3 and common ratio r = -2/3.
Sum the series: S = a / (1 - r) = (1/3) / (1 - (-2/3)) = (1/3) / (5/3) = 1/5 = 0.2.
Final answer: 0.2
A video solution is available for this question — log in and enroll to watch it.