to print the list of prime numbers between natural numbers "1" to "n" we have that "sqrt(n)" algorithm. is there any other algorithm so that the compiler takes even lesser time?????
#include <cmath>
constint MAX = 1000000;
int P[MAX];
int main()
{
int i, p, j;
P[2] = 2;
for ( i = 3; i < MAX; i += 2 )
{
P[i] = i;
}
for ( i = 3, p = sqrt(MAX); i <= p; i += 2 )
{
if ( P[i] != 0 )
{
for ( j = i * i; j <= MAX; j = j + 2 * i )
{
P[j] = 0;
}
}
}
return 0;
}
The Sieve of Eratothenes is probably one of the faster "simple" algorithms, though its primary drawback is that it requires storage of all primes less than N which means it does not scale to larger values of N.
Otherwise all you can do is optimize the above code.
One thing to do is move the calculation of sqrt(MAX) outside the for() loop since sqrt() will be called every time through the loop even though the result never changes.
[EDIT: never mind on the last statement, I just realized you already did this by precomputing sqrt(MAX) in the initializer.]
In terms of memory usage, all you really need is a boolean array to indicate whether or not the number is prime. That would reduce your memory utilization by a factor of 4, although that might not speed things up at all since now you will be performing non-aligned accessed.
And you could further reduce memory utilization (by a factor of 8) by using a bitset, although now each bit access requires a multiplication, mod, and addition, so that will certainly be slower.