ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (calls counts every call, including the first.)

What will be the output of the following pseudocode? (calls counts every call, including the first.)
Integer calls = 0
Function g(Integer n)
    calls = calls + 1
    if (n < 3)
        return 1
    end if
    return g(n - 1) + g(n - 3)
End Function

Print g(10), calls
  1. A. 28 28
  2. B. 28 55
  3. C. 19 55
  4. D. 28 37

Correct answer: B. 28 55

Values: g(0) = g(1) = g(2) = 1, then g(n) = g(n − 1) + g(n − 3): 2, 3, 4, 6, 9, 13, 19, 28, so g(10) = 28. Calls obey C(n) = 1 + C(n − 1) + C(n − 3) with C(0) = C(1) = C(2) = 1: C(3) = 3, 5, 7, 11, 17, 25, 37, C(10) = 55. 28 confuses the value with the number of calls (they agree only at the leaves); 37 is C(9).

More Pseudocode and Code Tracing questions

Exams that ask this topic