Exams › GATE › Technical
Consider the following C code segment: ```c 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)` denote the number of times the `for` loop is executed by the program on input `n`. Which of the following is true?
- `T(n) = O(√n)` and `T(n) = Ω(√n)`
- `T(n) = O(√n)` and `T(n) = Ω(1)`
- `T(n) = O(n)` and `T(n) = Ω(√n)`
- None of the above.
Correct answer: `T(n) = O(√n)` and `T(n) = Ω(1)`
Solution
The loop runs at most up to `√n`, so the upper bound is `O(√n)`. In the best case, it may terminate after a constant number of iterations if a small divisor is found, so the lower bound is `Ω(1)`. Thus the correct statement is `O(√n)` and `Ω(1)`.
Related GATE Technical questions
⚔️ Practice GATE Technical free + battle 1v1 →