ProgrammingHardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer memo[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
Integer calls = 0
Function F(n)
    calls = calls + 1
    If n < 2 Then Return n
    If memo[n] != -1 Then Return memo[n]
    memo[n] = F(n - 1) + F(n - 2)
    Return memo[n]
End Function
Integer r = F(8)
Print r, calls
  1. A. 21 15
  2. B. 21 67
  3. C. 21 8
  4. D. 21 9

Correct answer: A. 21 15

F(8) = 21. With memoisation each n from 2 to 8 expands once (7 expansions); each expansion makes two calls, so calls = 1 + 2 × 7 = 15. Without the memo the same function would make 67 calls.

More Pseudocode and Code Tracing questions

Exams that ask this topic