GATE / CS ARCHIVE

GATE CSE 2016 SET 2 / QUESTION 35

GATE CSE 2016 Set 2 Q35

Algorithms · Correctness, Invariants & Design · Full GATE CSE 2016 Set 2 paper

GATE 2016 Set 2, Q35 2 marks · MCQ
Report issue

Correctness, Invariants & Design

Question 35, GATE 2016: Code for positive X,Y: 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 invariant holds before every iteration? A X^Y=a^b; B (res*a)^Y=(res*X)^b; C X^Y=res*a^b; D X^Y=(res*a)^b.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under no-overflow arithmetic

The invariant is X^Y=res·a^b, C. Initially res=1, a=X, b=Y. An even step replaces(a, b) by(a², b/2), preserving a^b. An odd step multiplies res by a and decreases b by 1, preserving the product. At termination b=0, res=X^Y. This mathematical proof assumes intermediates fit the C int type; arbitrary positive inputs can overflow signed int and then lack defined C behavior.

For example X=2,Y=3 gives states (res,a,b)=(1,2,3),(2,2,2),(2,4,1),(8,4,0). The invariant product is 8 at each state. Option A fails once a factor moves into res; option D incorrectly raises res to b. Initialization, preservation and termination are three distinct obligations in a loop-invariant proof.

Original paper, page 34 · Answer key