1

I want know if the asymptotic complexity of this simple algorithm to find a prime number is O(n):

PrimeNumber(n)
Int i;
If (n%2=0) then { return "not prime"; }
Else {
  For(i=3;i<(√n)+1;i=i+2;){
    If (n%i=0) then {return "not prime";}
  }     
}
return "prime";
Gerard Rozsavolgyi
  • 4,834
  • 4
  • 32
  • 39
fenigo69
  • 53
  • 1
  • 8

1 Answers1

4

Time complexity is O(sqrt(n)), since the loop iterates itself (sqrt(n)+1-3)/2 times, which is in O(sqrt(n)).

Note that since O(sqrt(n)) is a subset of O(n), it is also correct to say it is O(n) - but that bound is not tight.

amit
  • 175,853
  • 27
  • 231
  • 333