Skip to content
Official PYQ · 2016

GATE CS 2016 Set 2 Q35 — Programming in C

Explain with AI

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
View worked solution

Answer: C

A loop invariant is a condition that remains true before and after each iteration of a loop. Let us verify the condition XY=res×abX^Y = res \times a^b:

  1. Initialization: Before the first iteration, res=1res = 1, a=Xa = X, and b=Yb = Y. Substituting these values into the expression: res×ab=1×XY=XYres \times a^b = 1 \times X^Y = X^Y The condition holds true initially.
  2. Maintenance: Assume the condition XY=res×abX^Y = res \times a^b holds before an iteration. Let res′res', a′a', and b′b' be the values after the iteration:
    • Case 1 (bb is even): a′=a2a' = a^2, b′=b/2b' = b/2, and res′=resres' = res. res′×(a′)b′=res×(a2)b/2=res×ab=XYres' \times (a')^{b'} = res \times (a^2)^{b/2} = res \times a^b = X^Y
    • Case 2 (bb is odd): res′=res×ares' = res \times a, a′=aa' = a, and b′=b−1b' = b - 1. res′×(a′)b′=(res×a)×ab−1=res×ab=XYres' \times (a')^{b'} = (res \times a) \times a^{b-1} = res \times a^b = X^Y
    In both cases, the relation is preserved.
  3. Termination: When the loop terminates, b=0b = 0. The invariant gives: XY=res×a0=res×1=resX^Y = res \times a^0 = res \times 1 = res This correctly yields the final computed value of XYX^Y.

Thus, the correct loop invariant is XY=res×abX^Y = res \times a^b.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions