GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 51

Bounds on the trial-division primality loop

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 2007 paper

GATE 2007, Q51 2 marks · MCQ
Report issue

Asymptotic Analysis & Recurrences

Question 51, GATE 2007: For the following printed C fragment, T(n) counts for-loop executions on input n. Which asymptotic bounds are intended?
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;
}
The source redeclares n; interpret the intended divisor-testing algorithm separately from literal C validity.
Options:
(A) O(√n) and Ω(√n)
(B) O(√n) and Ω(1)
(C) O(n) and Ω(√n)
(D) None of these
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Approach. A uniform lower bound must apply to easy inputs too. Even numbers terminate at i=2, whereas prime numbers make the loop test all candidate divisors through floor(√n).

2. Derivation and interpretation. Under the intended interpretation that n is the positive input integer, at most floor(sqrt(n))−1 candidate divisors are tested, so T(n)=O(sqrt(n)). For even n≥4, the first divisor i=2 causes immediate return, so T(n)=1 on an unbounded input family and no uniform Ω(sqrt(n)) lower bound is valid. For all sufficiently large n at least one iteration occurs, establishing Ω(1); B is therefore the intended answer. Prime n attain Θ(sqrt(n)). Source caveat: the printed function uses old-style IsPrime(n) and then declares int i,n inside its body, redeclaring its parameter n in the same scope. This is not valid C as printed; the algorithmic answer requires repairing the parameter declaration/removing the duplicate local n.

Original paper, page 12