Have you ever used an improved primality test such as Miller-Rabin algorithm? Also can you guys/gals think of any optimizations to this primality test?
bool isprime(ll n) {
for(int i = 2; i * i <= n; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
Nope,never.
Also in your algo, Include a condition for n=1. I have received several WAs in the past for forgetting 1 is not a prime.
For low constrain this algorithm is enough I think. Bt for high range seive of eratosthenes is better.
What would be the time complexity of the
Sieve of Eratosthenes
and how would you implement it?If you’re a Java boy, there is BigInteger.isProbablePrime(). Would recommend for any reasonable problem where you just need to check one prime if there are no other constraints to abuse
Me no Java boy, Me is C++ boy.
Yes a bit of optimization that I use as a result of the fact that all prime numbers greater than 3 are always of the form 6k+1 or 6k+5.
bool isPrime ( int n)
{
}
Change
i * i <= n
->i <= lim
wherelim
is precalculated assqrtn
will optimize a bit and may avoid overflow in some other similar functionsSure.
Currently it doesn't work for 64-bit integers as the signature would suggest. Either downshift
ll n
toint n
or account for integer overflow. To do the latter, for example, transformi * i
intoi * 1LL * i
.