Ehrlich sieve method [template]

sieve of prime numbers

General idea:

Enumerate each number, sieve out (b[i]=1;) its multiples and use it as a prime number, the multiples are no longer enumerated, so that all prime numbers are left after sieving.

Note that this algorithm has the disadvantage that it is not as time-complex as a linear sieve.

#include<iostream>
#include<cstdio>
#define MAXX 1000

MAXX can be larger, here is 1000 for convenience.

using namespace std;
bool b[MAXX];
int main()
{
    for(int i=2;i<=MAXX/2+1;i++)
    {
        if(b[i]==0)
        {
            for(int j=2;;j++)

The point! ! ! Don't start enumerating from 1, that will filter out all numbers that are not 1. 1 There should be a special judgment.

            {
                if(j>MAXX/i) break;
                b[i*j]=1;
            }
        }
    }
    for(int i=1;i<=MAXX;i++)
        if(b[i]==0) cout<<i<<endl;
}

If the definition of MAXX is relatively large, it is recommended to use freopen file output, otherwise it may not be possible to view all prime numbers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691698&siteId=291194637