素数线性筛模板

埃拉托斯特尼筛法(The sieve of Eratosthenes)

https://www.luogu.com.cn/problem/P3912

//只算出来了素数的个数
#include <cstdio>
const int N = 100000010;
bool isNotPrime[N];
int cnt;
int main() {
    int n;
    scanf("%d", &n);
    for (int i = 2; i * i <= n; i++)
        if (!isNotPrime[i])
            for (int j = i * i; j <= n; j += i)
                isNotPrime[j] = true;
    for (int i = 2; i <= n; i++)
        if (!isNotPrime[i]) cnt++;
    printf("%d\n", cnt);
    return 0;
}

欧拉筛法(The sieve of Euler)

证明

https://www.luogu.com.cn/problem/P3383

#include <cstdio>
const int N = 100000010;
bool isNotPrime[N];
int cnt, prime[N];
void table(int n) {
    for (int i = 2; i <= n; i++) {
        if (!isNotPrime[i]) prime[++cnt] = i;
        for (int j = 1; i * prime[j] <= n; j++) {
            isNotPrime[i * prime[j]] = true; //当prime[j]为某合数的最小质因数时,筛掉该合数
            if (i % prime[j] == 0) break; //保证每一个合数只被筛掉一次
        }
    }
}
int main() { 
    int n, q;
    scanf("%d%d", &n, &q);
    table(n);
    int c;
    while (q--) {
        scanf("%d", &c);
        printf("%d\n", prime[c]);
    }
    return 0;
}
posted @ 2020-02-20 17:13  watchphone  阅读(134)  评论(0编辑  收藏  举报