Assume that and 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);
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 and using repeated subtraction.
At each step of the while loop:
- If , it replaces with .
- If , it replaces with .
This process continues until . According to the properties of GCD, for . Thus, when the loop terminates, both and 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.
