ProgrammingVery hardGoldman Sachs OA · TCS Digital

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer mults = 0
Function pw(Integer x, Integer n)
    if (n == 0)
        return 1
    end if
    Integer t = pw(x, n / 2)
    t = t * t
    mults = mults + 1
    if (n mod 2 == 1)
        t = t * x
        mults = mults + 1
    end if
    return t
End Function
Print pw(2, 15), mults
  1. A. 32768 14
  2. B. 16384 8
  3. C. 32768 7
  4. D. 32768 8

Correct answer: D. 32768 8

The recursion visits n = 15, 7, 3, 1 (then 0). Each of these 4 levels squares once and, since all are odd, multiplies by x once: 8 multiplications for 2^15 = 32768. Naive repeated multiplication would need 14.

More Pseudocode and Code Tracing questions

Exams that ask this topic