返回首页 C++ 模板

埃式筛法模板

标记合数筛素数——O(n log log n) 的素数筛

素数筛 埃氏筛 筛法 GESP5
#include <bits/stdc++.h>
using namespace std;

const int N = 10000010;
bool notPrime[N];
int primes[N], cnt;

void sieve(int n) {
    notPrime[0] = notPrime[1] = true;
    for (int i = 2; i * i <= n; i++) {
        if (!notPrime[i]) {
            for (int j = i * i; j <= n; j += i)
                notPrime[j] = true;
        }
    }
    for (int i = 2; i <= n; i++)
        if (!notPrime[i]) primes[cnt++] = i;
}

int main() {
    int n = 100;
    sieve(n);
    cout << "素数个数: " << cnt << endl;  // 25
    for (int i = 0; i < cnt; i++)
        cout << primes[i] << " ";
    return 0;
}

📖 要点说明

⚠️ 常见错误