GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 41

Subtractive Euclidean algorithm

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2004 paper

GATE 2004, Q41 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 41, GATE 2004: What does this C-style fragment compute for positive integers x,y?
m=x; n=y;
while(m!=n) {
  if(m>n) m=m-n;
  else n=n-m;
}
printf("%d",n);
GFG option A is division by repeated subtraction; GateForum prints x+y instead.
Options:
(A) x/y by repeated subtraction
(B) x mod y by repeated subtraction
(C) Greatest common divisor of x,y
(D) Least common multiple of x,y
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. For positive x,y, each iteration replaces the larger of m,n by its difference with the smaller. This preserves gcd(m,n), keeps both positive, and strictly decreases m+n until m=n.

2. The printed common value is gcd(x,y). This is not ordinary repeated subtraction for division: the roles of the two operands change.

3. Teaching check: For x=12,y=8, the pairs evolve (12,8)→(4,8)→(4,4), so the answer is 4. Every common divisor is preserved by subtracting one operand from the other. The positive decreasing sum proves termination, completing both partial correctness and progress.

Original paper, page 6