线性筛素数

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e7 + 100;
const int MAXM = 3e3 + 10;

inline int read() {
    int x = 0, ff = 1; char ch = getchar();
    while(!isdigit(ch)) {
        if(ch == '-') ff = -1;
        ch = getchar();
    }
    while(isdigit(ch)) {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * ff;
}

inline void write(int x) {
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

int n, m, ans, v[MAXN], prime[MAXN]; 

void Primes(int n) {
    for(int i = 2; i <= n; ++i) {
        if(!v[i]) {
            v[i] = i;
            prime[++ans] = i;
        }
        for(int j = 1; j <= ans; ++j) {
            if(prime[j] > v[i] || prime[j] > n / i) break;
            v[i * prime[j]] = prime[j];
        } 
    }
}

int main() {
    n = read(); m = read();
    Primes(n);
    for(int i = 1; i <= m; ++i) {
        int x;
        x = read();
        if(v[x] == x) printf("Yes
");
        else printf("No
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AK-ls/p/10617266.html