-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_sieve.cpp
58 lines (49 loc) · 1.02 KB
/
linear_sieve.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
class LinearSieve {
public:
LinearSieve(size_t n) : is_prime_(n + 1, true) {
is_prime_[0] = false;
if (n >= 1) {
is_prime_[1] = false;
}
if (n < 2) {
return;
}
primes_.reserve(n / std::log(n));
for (size_t i = 2; i <= n; i++) {
if (is_prime_[i]) {
primes_.emplace_back(i);
}
for (size_t j : primes_) {
if (i * j > n) {
break;
}
is_prime_[i * j] = false;
if (i % j == 0) {
break;
}
}
}
}
const vector<size_t>& GetPrimes() const { return primes_; }
const vector<bool>& GetIsPrime() const { return is_prime_; }
private:
vector<bool> is_prime_;
vector<size_t> primes_;
};
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
int n, q;
cin >> n >> q;
LinearSieve sieve(n);
const auto& primes = sieve.GetPrimes();
for (int i = 0; i < q; ++i) {
int k;
cin >> k;
cout << primes[k - 1] << endl;
}
return 0;
}