----Eratosthenes Sieve method for generating prime sequence

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.