Article From:https://www.cnblogs.com/shuizhidao/p/9683542.html
int prime[MAXN], tag[MAXN];
void Get_Prime()
{
    Mem0(tag);
    int cnt = 0;
    for(int i = 2;i < MAXN;++i)
    {
        if(!tag[i])
            prime[cnt++] = i;
        for(int j = 0;j < cnt && i * prime[j] <= MAXN;++j)
        {
            tag[i * prime[j]] = 1;
            if(i % prime[j] == 0)
                break;
        }
    }
}

This is a picture given by many people online. Here’s just a map to simulate.

Or simulate the above example: N=20

 

Let me talk about my understanding (two key points on the Internet).

1、

        for(int j = 0;j < cnt && i * prime[j] <= MAXN;++j)

 

For this explanation, I think the explanation on the Internet is really not clear to me. Because I feel that I am more difficult to understand, but others I do not understand.

prime[j] Here are all primes less than or equal to I. For I * prime[j], let’s look at a prime number 2.

If there is no break below

When I = 3, there is 2 * 3 at this time.

When I = 4, there is 2 * 4 at this time. (in fact, the program runs to break here).

When I = 5, there is 2 * 5 at this time.

By analogy, we can see that the number of combinations related to prime [j] (any number can be multiplied by one or more prime numbers) is (prime [j] + 1 ~ i) * prime [j]

2、

            if(i % prime[j] == 0)
                break;

 

It’s said on the Internet that every combination is guaranteed to be sifted out by its smallest prime factor, so I’ll explain why this is the case. The main formula in the process forgot to find out what information and where it was aiming.

Let’s not talk about prime numbers. Let’s say compound numbers. Each compound number num can be expressed as the product of several prime numbers (Euler functions).

Let’s set a composite number of num, and the minimum prime factor of this composite number is a, then we get num = a^k * B.

1、When k is 1, Num = a * B (a < b)

2、When k = 1, Num = a^k * B

Notice here that we represent the sum of the above code as I * prime [j] = num; when i% prime [j] = = 0, prime [j] is the smallest prime number that makes up I (prime is arranged from small to large)Prime array, i.e. let I = C * prime [j], then num = C * prime [j] prime [j] = prime [j] ^ 2 * c; this corresponds to the above 2, although this inference does not prove sufficient and necessary conditionsBut it should be understood.

What about the top 1? It is not num = I * prime[j] = b * a (prime[j] < = I)

 

Link of this Article: Linear prime sieve

Leave a Reply

Your email address will not be published. Required fields are marked *