The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+4 votes
713 views

Assume that $X$ and $Y$ 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);
  1. Computes the LCM of two numbers

  2. Divides the larger number by the smaller number

  3. Computes the GCD of two numbers

  4. None of the above

asked in Algorithms by Veteran (59.7k points)
edited by | 713 views
0
while X <> Y && (X!=0 || Y!=0) do // I don't know if '&&' works in pascal
if  X > Y then                    //Even if this considered as comment or not.
    X := X - Y
else
    Y := Y - X;
write(X);

3 Answers

+12 votes
Best answer

Answer: C

Let $X = 3$ and $Y = 7$.
1st pass: $X = 3$, $Y = 4$
2nd pass: $X = 3$, $Y = 1$
3rd pass: $X = 2$, $Y = 1$
4th pass: $X = 1$, $Y = 1$
write $(X)$, which writes $1$.

Ref: http://www.naturalnumbers.org/EuclidSubtract.html

answered by Boss (34k points)
edited by
+2 votes

Apply Option Elimination

take X=6,Y=4

if Ans will 12 then LCM , 2 then GCD, 1 then Divides the larger number by the smaller number

Now Trace the code

Iteration1 :-X=2,Y=4

            2:-X=2,Y=2

Print 2 ; which is GCD

take another pair X=12,Y=8 which gives 4 means ans is GCD .

Hence C is the Correct Ans

answered by Boss (23.1k points)
0 votes
The algorithm is based on below facts.

If we subtract smaller number from larger (we reduce larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD.
answered by Active (1.2k points)

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

44,279 questions
49,767 answers
164,265 comments
65,853 users