The following is the implementation code of the Eratosthenes sieve method:
Boolean[] Sieveoferatosthenes (int max)
{
Boolean[] Flags = new Boolean[max + 1];
int count = 0;
init (flags);//Set the flags to true for all elements except the 0, 1 elements
int prime = 2;
while (Prime <= max)
{
Draw out the number of the remaining prime multiples
Crossoff (flags, prime);
Find the next value that is true
Prime = Getnextprime (flags, prime);
if (Prime >= flags.length)
{
Break
}
}
return to the flags;
}
void Crossoff (boolean[] flags, int prime)
{
/* Draw out the remaining number of prime multiples and we can
(prime*prime) Start, because if K*prime and K<prime,
This value has already been crossed out in previous iterations */
for (int i = prime*prime, i < flags.length; i + = prime)
{
Flags[i] = false;
}
}
int Getnextprime (boolean[] flags, int prime)
{
int next = prime + 1;
while (Next < Flags.length&&!flags[next])
{
next++;
}
return next;
}
There are some places in the code above that can be optimized, such as just putting an odd number into an array and halving the space required.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
----Eratosthenes Sieve method for generating prime sequence