GATE | GATE-CS-2015 (Set 1) | Question 65

Consider the following pseudo code, where x and y 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
(A) {r = qx + y ∧ r < y}
(B) {x = qy + r ∧ r < y}
(C) {y = qx + r ∧ 0 < r < y}
(D) { q + 1 0}


Answer: (B)

Explanation: The given pseudo code does following for given x and y which positive integers.

1) It initializes r as x.
2) It repeatedly subtracts y from r until r becomes
   smaller than y.  For every subtraction, it 
   increments count q.
3) Finally r contains remainder, i.e., x%y and q contains
   ⌊x/y⌋

See below pseudo code with comments.

begin
   q := 0  // q is going to contain floor(x/y)
   r := x  // r is going to contain x % y

// Repeatedly subtract y from x.
while r >= y do
   begin
      r := r – y
      q := q + 1
   end
end


Quiz of this Question

My Personal Notes arrow_drop_up