Quick and easy prime number test because...
Posted: Sun Jun 19, 2011 11:57 pm
This is a quick and easy prime number test because I'm seriously sick of searching all over the web for a faster way. So I wrote three and decided that the one with the least lines of code actually looks like it works better.
Oh and you must #include <math.h>
For more information look up Sieve of Eratosthenes and AKS. The codes based on both.
Code: Select all
bool isPrime(long n)
{
if (n < 2) return false;
if (n < 4) return true;
if (n % 2 == 0) return false; // if number modulo 2 returns 0 then it's even, and not prime
const unsigned int i = sqrt((double)n) + 1;
for (unsigned int j = 3; j <= i; j += 2)
{
if (n % j == 0)
return false;
}
return true;
}
For more information look up Sieve of Eratosthenes and AKS. The codes based on both.