跳到正文

个人记录

线性筛

chenzeyu0110约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

对于筛取素数我们可以用线性筛(欧拉筛)来得到素数vector数组

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
vector<int> v;
int n;
bool f[N];
void solve(int p) {
    for (int i=2;i<=p;i++) {
        if (!f[i])
            v.push_back(i);
        for (int vv:v) {
            if (i%vv==0)break;
            if (i*vv>n) break;
            f[i*vv]=true;
        }
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    solve(n);
    for (int vv:v) {
        cout<<vv<<" ";
    }
    cout<<endl;
    return 0;
}
原文