I\'ve been interested in the problem of finding a better prime number recognizer for years. I realize this is a huge area of academic research and study - my interest in this i
Here's my algorithm, Complexity remains O(n^0.5)
but i managed to remove some expensive operations in the code...
The algorithm's slowest part is the modulus
operation, i've managed to eliminate sqrt
or doing i * i <= n
This way i save precious cycles...its based on the fact that sum of odd numbers is always a perfect square.
Since we are iterating over odd numbers
anyway, why not exploit it? :)
int isPrime(int n)
{
int squares = 1;
int odd = 3;
if( ((n & 1) == 0) || (n < 9)) return (n == 2) || ((n > 1) && (n & 1));
else
{
for( ;squares <= n; odd += 2)
{
if( n % odd == 0)
return 0;
squares+=odd;
}
return 1;
}
}