P3383. 线性筛素数

考点

  • 线性筛

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
const int LEN = 1e7 + 50;
bitset<(int)1e8> vis;
int n, q, k, tot, pri[LEN];

void f() {
for (int i = 2; i <= n; ++i) {
if (!vis[i]) pri[++tot] = i;
for (int j = 1; j <= tot && 1ll * i * pri[j] <= n; ++j) {
vis[i * pri[j]] = 1;
if (i % pri[j] == 0) break;
}
}
}

int main() {
ios::sync_with_stdio(false);
cin >> n >> q;
f();
while (q--) {
cin >> k;
cout << pri[k] << endl;
}
return 0;
}

思路

线性筛的模板题