Prime number screening (Eppendorf linear mesh sieve +)

1. Erichsen sieve method

Rationale: from small to each of multiple primes general weed out
if a number is not the number of screens in front of it away, then it must be a prime number.
Reasons: it is not in front of 2 ~ p-1 in any multiple of a number, then it is a prime

Time complexity: n * log (log (n)), a near linear

const int N = 1e6+5;
bool isprime[N];
int prime[N];
int cnt;
void init(int n)
{
    isprime[1]=true;
    for(int i=2;i<=n;i++)
    {
        if(!isprime[i])
        {
            prime[++cnt]=i;
            for(int j=i+i;j<=n;j+=i)
                isprime[j]=true;
        }
    }
}

2. Linear sieve

Rationale: It is only the minimum number of each prime factor screened out, then each number will be screened once, the time complexity is o (n)

const int N = 1e6+5;
bool isprime[N];
int prime[N];
int cnt;
void init(int n)
{
    isprime[1]=true;
    for(int i=2;i<=n;i++)
    {
        if(!isprime[i])
           prime[cnt++]=i;
        for(int j=0;prime[j]<=n/i;j++)
        {
            isprime[prime[j]*i]=true;
            if(i%prime[j]==0)
                break;
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43693379/article/details/94362848