题目地址:
https://www.luogu.com.cn/problem/P3912
题目描述:
求
1
,
2
,
⋯
,
N
1,2,\cdots,N
1,2,⋯,N中素数的个数。
输入格式:
一行一个整数
N
N
N。
输出格式:
一行一个整数,表示素数的个数。
数据范围:
对于
40
%
40\%
40%的数据,
1
≤
N
≤
1
0
6
1 \le N \le 10^6
1≤N≤106。
对于
80
%
80\%
80%的数据,
1
≤
N
≤
1
0
7
1 \le N \le 10^7
1≤N≤107。
对于
100
%
100\%
100%的数据,
1
≤
N
≤
1
0
8
1 \le N \le 10^8
1≤N≤108。
直接用欧拉筛。参考https://blog.csdn.net/qq_46105170/article/details/113813830。代码如下:
#include <iostream>
using namespace std;
const int N = 1e8 + 10;
int n;
int p[N], cnt;
bool st[N];
void get_prime() {
for (int i = 2; i <= n; i++) {
if (!st[i]) p[cnt++] = i;
for (int j = 0; p[j] <= n / i; j++) {
st[p[j] * i] = true;
if (i % p[j] == 0) break;
}
}
}
int main() {
scanf("%d", &n);
get_prime();
printf("%d\n", cnt);
}
时空复杂度 O ( N ) O(N) O(N)。