Question
Consider the C program fragment below which is meant to divide by using repeated subtractions. The variables and are all unsigned int.
while (r >= y) {
r = r - y;
q = q + 1;
}
Which of the following conditions on the variables and before the execution of the fragment will ensure that the loop terminates in a state satisfying the condition x == (y*q + r)?
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 and remainder of divided by :
while (r >= y) {
r = r - y;
q = q + 1;
}
- Loop Invariant: At every step of the loop, the relation must be preserved.
Before entering the loop, if we set and , we have:During each iteration, decreases by and increases by 1:Thus, is an exact invariant. - Termination: The loop condition is
r >= y. For the loop to terminate, must eventually drop below . If , is always true forunsigned int, causing an infinite loop. Therefore, we must have .
Thus, the preconditions required are , , and , which corresponds to option C.
C
Overlooking that must be initialized to 0; if is not 0, 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.