GATE CS 2007 · Asymptotic Analysis & Recurrences

MCQ · 1 mark · Problem PROG-DIVC-0137

Consider the following C code segment:
int IsPrime(n)
{
    int i, n;
    for (i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            {printf("Not Prime"); return 0;}
    return 1;
}
Let \(T(n)\) denote the number of times the for loop is executed by the program on input \(n\). Which of the following is TRUE?
  1. A
    \(T(n)=O(\sqrt{n}) \; and \; T(n)=\Omega (\sqrt{n})\)
  2. B
    \(T(n)=O(n) \; and \; T(n)=\Omega (\sqrt{n})\)
  3. C
    \(T(n)=O(\sqrt{n}) \; and \; T(n)=\Omega (1)\)
  4. D
    None of the above

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{1\le T(n)\le\sqrt n}\]Worst case (\(n\) prime): the loop runs for every \(i\) from 2 to \(\lfloor\sqrt n\rfloor\), so \(T(n)=O(\sqrt n)\).Best case (\(n\) even): \(n\%2==0\) on the first iteration, so the loop runs once: \(T(n)=\Omega(1)\), and \(T(n)\) is not \(\Omega(\sqrt n)\) for all \(n\).So (A) and (B) fail (no \(\Omega(\sqrt n)\) lower bound) and (C) holds.Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com