Linear sieve of prime numbers → Euler sieve

[Title source]
https://www.acwing.com/problem/content/870/

[Title description]
Given a positive integer n, please find the number of prime numbers in 1∼n.

[Input format]
A total of one line, including the integer n.

【Output Format】
One line, including an integer, indicating the number of prime numbers in 1∼n.

[Data range]
1≤n≤10^6

[Input sample]
8

[Output sample]
4

[Algorithm analysis]
Ordinary prime number sieve method, that is, the multiples of all numbers x within a given number n are kx(k≥ 2) Sieve them all out.
Obviously, it can be seen from the figure below that the same number may be repeatedly screened out
by multiple prime numbers . 6 and 12 in the figure below are repeatedly screened out. This requires optimization, and the Euler sieve is a linear sieve of prime numbers . The principle is to let each composite number be screened out only by its smallest prime factor , so that each composite number will only be screened once.

 【Algorithm code】

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e6+5;
int p[maxn];
bool st[maxn];
int cnt;

void getNum(int n) {
    for(int i=2; i<=n; i++) {
        if(!st[i]) p[cnt++]=i;
        for(int j=0; p[j]*i<=n; j++) {
            st[p[j]*i]=true;
            if(i%p[j]==0) break;
        }
    }
}

int main() {
    int n;
    cin>>n;
    getNum(n);
    cout<<cnt<<endl;
    
    return 0;
}

/*
in:8
out:4
*/

[References]
https://zhuanlan.zhihu.com/p/494328631
https://www.acwing.com/solution/content/7950/





 

Guess you like

Origin blog.csdn.net/hnjzsyjyj/article/details/132352060