-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmented Sieve.cpp
More file actions
67 lines (53 loc) · 1.48 KB
/
Segmented Sieve.cpp
File metadata and controls
67 lines (53 loc) · 1.48 KB
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
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
vector<ull> primes;
void sieve(ull n)
{
bool mask[n+5];
memset(mask, false, sizeof(mask));
ull lim = sqrt(n) + 1;
primes.push_back(2);
for(ull i = 3; i <= n; i += 2)
{
if(!mask[i])
{
primes.push_back(i);
if(i <= lim)
for(ull j = i*i; j <= n; j += i*2)
mask[j] = true;
}
}
}
void primesInRange(ull low, ull high)
{
low = max(low, 2ull);
sieve(sqrt(high)+1);
ull n = high - low + 1;
bool mask[n+5];
memset(mask, false, sizeof(mask));
for(int i = 0; i < primes.size(); ++i)
{
/* Find the minimum number in [low..high] that is
a multiple of prime[i] (divisible by prime[i]) */
ull loLim = floor(low / primes[i]) * primes[i];
if(loLim < low)
loLim += primes[i];
if(loLim == primes[i])
loLim += primes[i];
/* Mark multiples of prime[i] in [low..high]:
We are marking j - low for j, i.e. each number
in range [low, high] is mapped to [0, high - low] */
for(ull j = loLim; j <= high; j += primes[i])
mask[ j-low ] = true;
}
for(ull i = low; i <= high; i++)
if(!mask[ i-low ])
cout << i << " ";
}
int main()
{
int low = 0, high = 200;
primesInRange(low, high);
return 0;
}