Skip to content
Official PYQ · 2004

GATE CS 2004 Q41 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

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

Choose one option
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 xx and yy using repeated subtraction.

Step-by-Step Analysis:

  • The program initializes m=xm = x and n=yn = y.
  • The while(m != n) loop continues as long as mm and nn are not equal.
  • Inside the loop:
    • If m>nm > n, it replaces mm with m−nm - n. This is based on the mathematical property:
      gcd⁡(m,n)=gcd⁡(m−n,n)for m>n\gcd(m, n) = \gcd(m - n, n) \quad \text{for } m > n
    • If n>mn > m, it replaces nn with n−mn - m, based on:
      gcd⁡(m,n)=gcd⁡(m,n−m)for n>m\gcd(m, n) = \gcd(m, n - m) \quad \text{for } n > m
  • When mm becomes equal to nn, the loop terminates, and the common value (which is gcd⁡(x,y)\gcd(x, y)) is printed.

Example Trace:

Let x=15x = 15 and y=9y = 9:

  1. Initially, m=15,n=9m = 15, n = 9. Since m≠nm \neq n:
    • m>n  ⟹  m=15−9=6m > n \implies m = 15 - 9 = 6.
  2. Now, m=6,n=9m = 6, n = 9. Since m≠nm \neq n:
    • n>m  ⟹  n=9−6=3n > m \implies n = 9 - 6 = 3.
  3. Now, m=6,n=3m = 6, n = 3. Since m≠nm \neq n:
    • m>n  ⟹  m=6−3=3m > n \implies m = 6 - 3 = 3.
  4. Now, m=3,n=3m = 3, n = 3. Since m==nm == n, the loop terminates.
  5. The program prints n=3n = 3, which is indeed gcd⁡(15,9)\gcd(15, 9).

Therefore, the program computes the greatest common divisor of xx and yy.

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

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