What would be the time complexity of this function
bool prime(int n) {
if(n <= 1) {
return false;
} else if(n <= 3) {
return true;
} else if(n % 2 == 0 || n % 3 == 0) {
return false;
} else {
for(int i = 5; i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
}
return true;
}
If I had to guess, it would be
O(sqrt(log(n)))
Each if is constant time.
for
loop is executed untili * i
reachesn
this means it is executedsqrt(n) / 6
times. So complexity isO(sqrt(n))
.It doesn't meter that density of prime numbers is proportional to
1/log(n)
(probably this is source oflog(n)
in your solution.Note that time complexity (no adjective) usually is consider as worst time complexity:
Time complexity - Wikipedia
Average time complexity is much harder to compute in this case. You would have to prove how fast loop terminates on average when
n
is not a prime number.