Question

The following function computes XYX^Y for positive integers XX and YY.

int exp(int X, int Y) {
    int res = 1, a = X, b = Y;
    while ( b != 0 ){
        if ( b%2 == 0) { a = a*a; b = b/2; }
        else
        { res = res*a; b = b-1; }
    }
    return res;
}

Which one of the following conditions is TRUE before every iteration of the loop?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2016 answer key

Solution

Identify the loop invariant of the binary exponentiation algorithm.

The function implements the classic binary exponentiation algorithm (exponentiation by squaring) to compute XYX^Y.

Trace the loop variables:

  • Initial state: res = 1, a = X, b = Y.
    Testing Option (C): res×ab=1×XY=XY\text{res} \times a^b = 1 \times X^Y = X^Y. The relation holds initially.

Inductive step: Assume XY=res×abX^Y = \text{res} \times a^b holds before an iteration with b>0b > 0:

  • Case 1: bb is even (b%2==0b \% 2 == 0).
    The code updates anew=a2a_{\text{new}} = a^2 and bnew=b/2b_{\text{new}} = b / 2, leaving res unchanged.
    resnew×(anew)bnew=res×(a2)b/2=res×ab=XY\text{res}_{\text{new}} \times (a_{\text{new}})^{b_{\text{new}}} = \text{res} \times (a^2)^{b/2} = \text{res} \times a^b = X^Y
  • Case 2: bb is odd (b%2≠0b \% 2 \ne 0).
    The code updates resnew=res×a\text{res}_{\text{new}} = \text{res} \times a and bnew=b−1b_{\text{new}} = b - 1, leaving a unchanged.
    resnew×(anew)bnew=(res×a)×ab−1=res×ab=XY\text{res}_{\text{new}} \times (a_{\text{new}})^{b_{\text{new}}} = (\text{res} \times a) \times a^{b-1} = \text{res} \times a^b = X^Y

In both branches, the quantity res×ab\text{res} \times a^b is invariant and remains equal to XYX^Y.

When the loop terminates (b=0b = 0):

res×a0=res=XY\text{res} \times a^0 = \text{res} = X^Y

Therefore, the condition XY=res∗abX^Y = \text{res} * a^b is TRUE before every iteration of the loop (Option C).

Final answer

C

Common trap

Selecting XY=abX^Y = a^b, which only holds at initialization and is violated as soon as res is multiplied.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2016 Computer Science and Information Technology (CS) Session 2
Question
45 of 65, printed as CS Q.35
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.