Consider the following C program
main()
{
int x, y, m, n;
scanf("%d %d", &x, &y);
/* Assume x>0 and y>0*/
m = x; n = y;
while(m != n)
{
if (m > n)
m = m-n;
else
n = n-m;
}
printf("%d", n);
}
The program computes
View worked solution
Answer: C
The given C program implements the classic Euclidean algorithm for finding the Greatest Common Divisor (GCD) of two positive integers and using repeated subtraction.
Step-by-Step Analysis:
- The program initializes and .
- The
while(m != n)loop continues as long as and are not equal. - Inside the loop:
- If , it replaces with . This is based on the mathematical property:
- If , it replaces with , based on:
- If , it replaces with . This is based on the mathematical property:
- When becomes equal to , the loop terminates, and the common value (which is ) is printed.
Example Trace:
Let and :
- Initially, . Since :
- .
- Now, . Since :
- .
- Now, . Since :
- .
- Now, . Since , the loop terminates.
- The program prints , which is indeed .
Therefore, the program computes the greatest common divisor of and .
Free practice · Your answers on this page are not saved.
