0
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;
}

Here the loop executes for $ \Theta (\sqrt{n}) $ time . But my teacher said that it is not because the lower bound is $ \omega (1) $ I was not able to understand why it so .

Q1] Could some of you explain which one of us is right justifying reason ?

Q2] What is the importance of " return 0 " ? What would have been the change if there had no " return 0 inside looping function ?

Q3] In general What is the meaning of return 0, 1, -1 in C programming language ? I have read this from stackoverflow but that didn't solve . Need little bit explanation

Akhil Nadh PC
  • 348
  • 3
  • 15

1 Answers1

4

The loop executes at most $O(\sqrt n)$ times because i is incremented in every iteration of the loop. You claim that it is also executed at least $\Omega(\sqrt n)$ times. This is not true because it has an early exit (the return statement). For example for even numbers the function returns during the first iteration.

If you recall the definition of $\Omega$, we have $f(n) \in \Omega(g(n))$ if there is some constant $n_0$ such that for all $n>n_0$ we have $c*g(n) < f(n)$ for some constant $c$. By this definition the runtime of your program can't be $\Omega(\sqrt n)$ because the loop makes only one iteration for infinitely many inputs (that is, you can't find a suitable $n_0$).

You can of course restrict your analysis to the worst case ($n$ is a prime number). Then you are correct in saying that the runtime is $\Theta(\sqrt n)$. There is a question about the relation of $O$, $\Omega$, best and worst case in case you find this confusing.

adrianN
  • 5,991
  • 19
  • 27