Algorithm template-prime number judgment / prime number sieve method

Prime number: A number that can only be divided by 1 and itself is called a prime number, otherwise it is a composite number.

Prime number judgment: a number n, bring all the numbers less than n greater than 1 one by one, if any one can be divided, the judgment is composite, if not, it is a prime number.

Optimization: The factors of a composite number appear in pairs (assuming n = i * j; i <j; when we judge that i is a factor of n, we also judge that j is a factor of n), so we do not have to To judge all the numbers from 2 to n-1, just judge from 2 to sqrt (n).

bool isprim(unsigned x)
{
    if(x<2)return false;
    for(unsigned i=2;i*i<=x;i++)
        if(x%i==0)return false;
    return true;
}

 

Sometimes, you need to repeatedly check whether a number is a prime number in the program, you can save the judgment result in an array for easy query. This is the sieve method of prime numbers.

Ehrlich sieve method: O (n log n), screening out numbers that are not prime numbers. Some numbers will be repeatedly filtered, such as 12: 2 * 6 = 3 * 4 = 12; so 12 will be filtered by 2 and 3.

const int maxn=1000009;
bool noprime[maxn];
void isprim()
{
    memset(noprime,0,sizeof(noprime));
    noprime[0]=noprime[1]=1;
    for(int i=2;i*i<maxn;i++)
        if(!noprime[i])
            for(int j=i*i;j<maxn;j+=i)
                noprime[j]=true;
}

 Euler sieve / linear sieve: O (n), using prime factorization, any integer has its unique prime factor representation, so it is guaranteed that each number is only sieved once.

const int maxn=100009;
int prime[maxn+1];            //prime[0]用来储存素数个数 
void getPrime()
{
    memset(prime,0,sizeof(prime));
    for(int i=2;i<=maxn;i++){
        if(!prime[i])prime[++prime[0]]=i;
        for(int j=1;j<=prime[0]&&prime[j]*i<=maxn;j++){
            prime[prime[j]*i]=1;
            if(i%prime[j]==0)break;
        }
    }
}

 

  

Guess you like

Origin www.cnblogs.com/xinwang-coding/p/12724153.html