Skip to content
Official PYQ · 2007

GATE CS 2007 Q51 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following C program segment:

int IsPrime (n)
    {
        int i, n;
        for (i=2; i<=sqrt(n);i++)
            if(n%i == 0)
                {printf("Not Prime \n"); return 0;}
        return 1;
    }

Let T(n)T(n) denote number of times the forfor loop is executed by the program on input nn. Which of the following is TRUE?
 

Choose one option
View worked solution

Answer: B

To find the correct asymptotic bounds for T(n)T(n), the number of times the for loop is executed, we need to analyze the best-case and worst-case scenarios of the algorithm.

1. Worst-Case Analysis (Upper Bound OO)

The worst-case occurs when nn is a prime number. In this case, the condition n % i == 0 is never satisfied for any ii in the range [2,n][2, \sqrt{n}].

  • The loop variable ii runs from 22 up to ⌊n⌋\lfloor\sqrt{n}\rfloor.
  • The number of iterations is approximately n−1\sqrt{n} - 1.
  • Therefore, the maximum number of iterations is bounded above by n\sqrt{n}, which gives:
T(n)=O(n)T(n) = O(\sqrt{n})

2. Best-Case Analysis (Lower Bound Ω\Omega)

The best-case occurs when nn is an even number greater than 22 (e.g., n=4,6,8,…n = 4, 6, 8, \dots).

  • In the very first iteration where i=2i = 2, the condition n % 2 == 0 evaluates to true.
  • The function immediately prints "Not Prime" and returns 00.
  • Thus, the loop executes exactly 11 time.
  • Since the loop executes at least a constant number of times for any input n≥2n \ge 2, we have:
T(n)=Ω(1)T(n) = \Omega(1)

Conclusion

Combining both bounds, we get:

T(n)=O(n)andT(n)=Ω(1)T(n) = O(\sqrt{n}) \quad \text{and} \quad T(n) = \Omega(1)

Hence, the correct option is B.

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

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