ProgrammingHardCapgemini · Infosys pattern

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

What will be the output of the following pseudocode (fast exponentiation)? (All variables are integers, so / is integer division.)
Integer calls = 0
Function fp(Integer a, Integer b)
    calls = calls + 1
    if (b == 0)
        return 1
    end if
    Integer h = fp(a, b / 2)
    if (b mod 2 == 0)
        return h * h
    end if
    return a * h * h
End Function

Print fp(3, 7), calls
  1. A. 2187 3
  2. B. 2187 4
  3. C. 3 4
  4. D. 2187 7

Correct answer: B. 2187 4

3^7 = 2187. b halves at each level: 7->3->1->0, which is exactly 4 recursive calls (including the base case), matching the exponential-by-squaring pattern.

More Pseudocode and Code Tracing questions

Exams that ask this topic