ProgrammingHardInfosys · Capgemini pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer calls = 0
Integer Function f(Integer n)
    calls = calls + 1
    if (n <= 2) return 1
    return f(n - 1) + f(n - 3)
End Function
Print f(7), calls
  1. A. 9 9
  2. B. 9 17
  3. C. 13 17
  4. D. 9 15

Correct answer: B. 9 17

f(3..7) = 2, 3, 4, 6, 9. Calls satisfy C(n) = 1 + C(n − 1) + C(n − 3) with C(n) = 1 for n ≤ 2: C(3) = 3, C(4) = 5, C(5) = 7, C(6) = 11, C(7) = 17. The number of calls grows faster than the value's own recursion suggests.

More Pseudocode and Code Tracing questions

Exams that ask this topic