ProgrammingModerateTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer Function g(Integer n)
    if (n <= 1) return n
    return g(n - 1) + 2 * g(n - 2)
End Function
Print g(6)
  1. A. 21
  2. B. 31
  3. C. 11
  4. D. 43

Correct answer: A. 21

g(0) = 0, g(1) = 1, then 1, 3, 5, 11, 21: each term is the previous plus twice the one before (the Jacobsthal numbers, (2ⁿ − (−1)ⁿ)/3). Naive recursion is exponential; a loop is O(n).

More Pseudocode and Code Tracing questions

Exams that ask this topic