Euler sieve (for prime numbers)

Source: Internet
Author: User
Euler sieve (for prime numbers)

Linear sieve with an O (n) degree of complexity. Compared to the composite, it is more efficient to repeat the labeling of the labeled markers. The Euler sieve decomposes the composite into the form of (min factorization * a composite) and determines whether the current composite has been marked by a minimum of factorization.
  

const int MAXN = 101;   Table length
int PRIME[MAXN], pnum = 0;    Prime record Prime, pnum number of elements 
bool P[maxn] = {false};        P record whether the current number is sieved to

void Eulersieve (int n)    ///lookup record 2-n of the primes
{for
    (int i = 2; I <= n; i++)
    {
        if (P[i] = = False)  //If not sifted, then prime
            prime[pnum++] = i;
        for (j = 0; J < Pnum; J + +)
        {
            if (i * prime[j] > N)      //Jump out of break when the composite to be marked is out of range
                ;
            P[i * Prime[j]] = true;     Mark multiples of the number of recorded primes
            if (i% prime[j] = = 0)      //Key step break;}}
}

The difficulty of Euler sieve is to understand if (i% prime[j] = = 0) This step, when I is prime[j] integer times, remember m = i/prime[j], then I * prime[j+1] can become (M * prime[j+1]) * prime [j], this indicates that I * prime[j+1] is an integer multiple of prime[j], does not need to be marked (after which will be prime[j] * A number of marks), for prime[j+2] and after the prime of the same way, jump directly out of the loop, so that the repetition of the tag is avoided.

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.