Question

Consider the C program fragment below which is meant to divide xx by yy using repeated subtractions. The variables x,y,qx, y, q and rr are all unsigned int.

while (r >= y) {
    r = r - y;
    q = q + 1;
}

Which of the following conditions on the variables x,y,qx, y, q and rr before the execution of the fragment will ensure that the loop terminates in a state satisfying the condition x == (y*q + r)?

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

Solution

Analyze the loop invariant and termination conditions for the integer division by repeated subtraction algorithm.

The given algorithm computes quotient qq and remainder rr of xx divided by yy:

while (r >= y) {
    r = r - y;
    q = q + 1;
}
  1. Loop Invariant: At every step of the loop, the relation x=y⋅q+rx = y \cdot q + r must be preserved.
    Before entering the loop, if we set q=0q = 0 and r=xr = x, we have:
    y⋅q+r=y⋅0+x=xy \cdot q + r = y \cdot 0 + x = x
    During each iteration, rr decreases by yy and qq increases by 1:
    y(q+1)+(r−y)=yq+y+r−y=yq+r=xy(q + 1) + (r - y) = yq + y + r - y = yq + r = x
    Thus, x=y⋅q+rx = y \cdot q + r is an exact invariant.
  2. Termination: The loop condition is r >= y. For the loop to terminate, rr must eventually drop below yy. If y=0y = 0, r≥0r \ge 0 is always true for unsigned int, causing an infinite loop. Therefore, we must have y>0y > 0.

Thus, the preconditions required are q==0q == 0, r==xr == x, and y>0y > 0, which corresponds to option C.

Final answer

C

Common trap

Overlooking that qq must be initialized to 0; if qq is not 0, y⋅q+r≠xy \cdot q + r \ne x initially.

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

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 2
Question
37 of 65, printed as CS Q.37
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.