ProgrammingHardCapgemini · 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.)
Function power(Integer a, Integer b)
    if (b == 0)
        return 1
    end if
    Integer half = power(a, b / 2)
    if (b mod 2 == 0)
        return half * half
    end if
    return a * half * half
End Function

Print power(2, 10)
  1. A. 512
  2. B. 100
  3. C. 1024
  4. D. 2048

Correct answer: C. 1024

This is fast exponentiation: b halves at each level (10->5->2->1->0), and the results are squared back up (and multiplied by a once when b is odd), correctly computing 2^10 = 1024.

More Pseudocode and Code Tracing questions

Exams that ask this topic