ProgrammingModerateInfosys · Capgemini pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer Function fun(Integer a, Integer b)
    if (b == 0) return 1
    if (b mod 2 == 0)
        Integer t = fun(a, b / 2)
        return t * t
    end if
    return a * fun(a, b - 1)
End Function
Print fun(3, 5)
  1. A. 125
  2. B. 15
  3. C. 243
  4. D. 81

Correct answer: C. 243

fun computes aᵇ by fast exponentiation: 3⁵ = 3 · (3²)² = 3 · 81 = 243. Odd b peels off one factor, even b squares a half-power, so the call count is O(log b).

More Pseudocode and Code Tracing questions

Exams that ask this topic