Skip to content
Official PYQ · 1995

GATE CS 1995 Q2.3 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Assume that XX and YY are non-zero positive integers. What does the following Pascal program segment do?

while X <> Y do
if  X > Y then
    X := X - Y
else
    Y := Y - X;
write(X);
Choose one option
View worked solution

Answer: C

The given program segment implements the classic Euclidean algorithm for finding the Greatest Common Divisor (GCD) of two positive integers XX and YY using repeated subtraction.

At each step of the while loop:

  • If X>YX > Y, it replaces XX with X−YX - Y.
  • If Y>XY > X, it replaces YY with Y−XY - X.

This process continues until X=YX = Y. According to the properties of GCD, gcd⁡(X,Y)=gcd⁡(X−Y,Y)\gcd(X, Y) = \gcd(X - Y, Y) for X>YX > Y. Thus, when the loop terminates, both XX and YY hold the value of the GCD of the original two numbers, which is then printed.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions