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 denote number of times the loop is executed by the program on input . Which of the following is TRUE?
View worked solution
Answer: B
To find the correct asymptotic bounds for , 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 )
The worst-case occurs when is a prime number. In this case, the condition n % i == 0 is never satisfied for any in the range .
- The loop variable runs from up to .
- The number of iterations is approximately .
- Therefore, the maximum number of iterations is bounded above by , which gives:
2. Best-Case Analysis (Lower Bound )
The best-case occurs when is an even number greater than (e.g., ).
- In the very first iteration where , the condition
n % 2 == 0evaluates to true. - The function immediately prints "Not Prime" and returns .
- Thus, the loop executes exactly time.
- Since the loop executes at least a constant number of times for any input , we have:
Conclusion
Combining both bounds, we get:
Hence, the correct option is B.
Free practice · Your answers on this page are not saved.
