Files
python/TangDou/LuoGuBook/P5723_EulerSieve_Prepare.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

36 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
/**
原理https://www.luogu.com.cn/blog/hahahage/ou-la-shai-fa
*/
using namespace std;
const int N = 1e5 + 10; //可能的质数个数上限(靠猜的~)
int primes[N], cnt; // primes[]存储所有素数
bool st[N]; // st[x]存储x是否被筛掉
void get_primes(int n) {
//准备筛选每个数
for (int i = 2; i <= n; i++) {
//没有被标识过,就增加到质数数组中去
if (!st[i]) primes[cnt++] = i;
// 下面的代码的用途:筛出合数
// 重点:
// 1、不管是质数还是合数都要进行检查此处与埃筛不一样
// 2、从小到大枚举已知质数表注意这里有一个小技巧就是primes[j]*i<=n,因为要筛出i的质数倍i的质数倍都大于n了就没有必要继续了
for (int j = 0; primes[j] * i <= n; j++) {
st[primes[j] * i] = true; //结识为已筛出
// x只会被它最小的质因子筛掉
if (i % primes[j] == 0) break;
}
}
}
int main() {
//通过欧拉筛法求1e5以内所有的质数
get_primes(10000);
//输出结果结果在primes数组中cnt是数量
for (int i = 0; i < cnt; i++)
cout << primes[i] << " ";
return 0;
}