ProgrammingModerateCapgemini · Infosys pattern

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 calls = 0
Function power(Integer a, Integer b)
    calls = calls + 1
    if (b == 0)
        return 1
    end if
    Integer t = power(a, b / 2)
    if (b mod 2 == 0)
        return t * t
    end if
    return a * t * t
End Function

Print power(3, 5), calls
  1. A. 243 3
  2. B. 125 4
  3. C. 243 4
  4. D. 243 5

Correct answer: C. 243 4

This is fast exponentiation: b goes 5 → 2 → 1 → 0, so there are 4 calls. Going back up: b = 0 gives 1, b = 1 gives 3, b = 2 gives 9, b = 5 gives 3 × 81 = 243.

More Pseudocode and Code Tracing questions

Exams that ask this topic