Question

Consider the following pseudo code, where xx and yy are positive integers:

begin
    q := 0
    r := x
    while r >= y do
    begin
        r := r - y
        q := q + 1
    end
end

The post condition that needs to be satisfied after the program terminates is:

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2015 answer key

Solution

Determine the loop invariant and termination condition of the standard integer division algorithm.

The algorithm implements integer division of positive integer xx by positive integer yy using repeated subtraction:

  • Initially: q=0,r=xq = 0, r = x.
    At initialization: x=0⋅y+x=q⋅y+rx = 0 \cdot y + x = q \cdot y + r.
  • Loop body: at each step, rr is decremented by yy and qq is incremented by 11:
    (q+1)y+(r−y)=qy+y+r−y=qy+r=x.(q + 1)y + (r - y) = qy + y + r - y = qy + r = x.
    Thus, the loop invariant x=qy+rx = qy + r holds throughout.
  • Termination: the while loop while r >= y terminates when r≥yr \ge y becomes false, i.e., r<yr < y.

Combining the invariant and termination condition:

{x=qy+r∧r<y}.\{x = qy + r \land r < y\}.

This matches option B.

Final answer

B

Common trap

Switching xx and yy in the division formula or postcondition relation.

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

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
43 of 65, printed as CS Q.33
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.