-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem4739.cpp
83 lines (66 loc) · 1.46 KB
/
problem4739.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector<int> findPrimes(int n)
{
vector<int> primes;
vector<bool> isPrime(n + 1, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++)
{
if (isPrime[i])
{
for (int j = i * i; j <= n; j += i)
isPrime[j] = false;
}
}
for (int i = 2; i <= n; i++)
if (isPrime[i])
primes.push_back(i);
return primes;
}
void segmentedSieve(int l, int r)
{
if (l < 2)
l = 2;
int limit = floor(sqrt(r)) + 1;
vector<int> primes = findPrimes(limit - 1);
int low = l;
int high = l + limit;
r++;
vector<bool> mark(limit);
while (low < r)
{
if (high > r)
high = r;
mark.clear();
mark.resize(high - low);
fill(mark.begin(), mark.end(), true);
for (int p : primes)
{
int loLim = floor(low / p) * p;
if (loLim < low)
loLim += p;
if (loLim == p)
loLim *= p;
for (int i = loLim; i < high; i += p)
{
mark[i - low] = false;
}
}
for (int i = low; i < high; i++)
{
if (mark[i - low])
cout << i << ' ';
}
low += limit;
high += limit;
}
}
int main()
{
int l, r;
cin >> l >> r;
segmentedSieve(l, r);
}