-
Notifications
You must be signed in to change notification settings - Fork 0
/
segmented_sieve.cpp
89 lines (76 loc) · 1.63 KB
/
segmented_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
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
84
85
86
87
88
89
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
vector<int> primes;
// To get all the primes till sqrt(n)
void simpleSieve(int x)
{
vector<bool> isPrime(x + 1, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i <= x; i++)
{
if (isPrime[i])
{
for (int m = i * i; m <= x; m += i)
{
isPrime[m] = false;
}
}
}
for (int i = 2; i <= x; i++)
{
if (isPrime[i])
{
primes.push_back(i);
}
}
}
// To get primes in the segments (by looping through the list of primes made using simple sieve)
void segmentedSieve(int low, int high, vector<int> &ans)
{
vector<int> isPrime(high - low + 1, true);
for (int p : primes)
{
// To find first multiple of p
int s = low / p * p;
if (s < low)
{
s += p;
}
// Cancelling out the factors of p
for (int i = s; i <= high; i += p)
{
isPrime[i - low] = false;
}
}
for (int i = 0; i < isPrime.size(); i++)
{
if (isPrime[i])
{
ans.push_back(i + low);
}
}
}
int main()
{
primes.clear();
int n;
cout<<"Enter the number: ";
cin >> n;
simpleSieve((int)floor(sqrt(n)));
vector<int> ans;
// For every segment, we call segmentedSieve()
int updateVal = floor(sqrt(n));
for (int l = 2; l < n; l += updateVal)
{
int r = min(l + updateVal - 1, n - 1);
segmentedSieve(l, r, ans);
}
for (int p : ans)
{
cout << p << " ";
}
cout << endl;
}