GATE / CS ARCHIVE

SIMILAR QUESTIONS / PROGRAMMING IN C

Establish repeated-subtraction division invariants

2 questions solved the same way, newest first. Back to Programming in C

How these are solved

Both use r-=y;q++ under r>=y. Establish x=y*q+r and positive divisor to prove progress; exit yields r<y.

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 37, GATE 2017: Unsigned integers x,y,q,r are used for division by repeated subtraction: while(r>=y){r=r-y; q=q+1;}. Which initial condition guarantees termination and final x==y*q+r? A:(q==r)&&(r==0). B:(x>0)&&(r==x)&&(y>0). C:(q==0)&&(r==x)&&(y>0). D:(q==0)&&(y>0).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. To preserve the intended division relation, use the invariant x=yq+r. Option C initializes q=0 and r=x, so the invariant holds before the loop. It also ensures y>0.

2. One iteration replaces r by r-y and q by q+1. Therefore y(q+1)+(r-y)=yq+r=x: the invariant is preserved. The guard r≥y prevents unsigned subtraction underflow.

3. Since y is positive, r decreases on every iteration and cannot decrease forever. At exit 0≤r<y, so q and r are the quotient and remainder. B leaves q unconstrained, D leaves r unconstrained, and A neither establishes the invariant for arbitrary x nor excludes y=0. C is the sufficient condition.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 65, GATE 2015: For positive integers x,y: q:=0; r:=x; while r≥y do {r:=r−y; q:=q+1}. Which postcondition holds? A r=qx+y and r<y; B x=qy+r and r<y; C y=qx+r and 0<r<y; D q+1<r−y and y>0.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Prove the invariant x=qy+r by initialization and preservation: (q+1)y+(r−y)=qy+r. The guard ensures subtracting y never makes r negative. Since positive y decreases r at every step, the loop terminates and the false guard gives r<y. Therefore q is the integer quotient and r the remainder with 0≤r<y. A remainder may be zero, so a strict lower bound such as that in C would be wrong.

Solution: Initially q=0, r=x, so x=qy+r. Each iteration replaces r by r−y and q by q+1, preserving that invariant. Positive y decreases nonnegative r on every iteration; termination gives 0≤r<y. Hence the listed postcondition x=qy+r and r<y is B; the full invariant also supplies the nonnegative lower bound.

Original paper, page 25 · Answer key