-
Notifications
You must be signed in to change notification settings - Fork 12
/
prime_printer.cpp
77 lines (60 loc) · 1.48 KB
/
prime_printer.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
/* C++ program to print print all primes smaller than
n using segmented sieve by knightvertrag*/
#include <bits/stdc++.h>
using namespace std;
void simpleSieve(int limit, vector<int> &prime)
{
bool mark[limit + 1];
memset(mark, true, sizeof(mark));
for (int p = 2; p * p < limit; p++)
{
if (mark[p] == true)
{
for (int i = p * 2; i < limit; i += p)
mark[i] = false;
}
}
for (int p = 2; p < limit; p++)
{
if (mark[p] == true)
{
prime.push_back(p);
cout << p << " ";
}
}
}
void segmentedSieve(int n)
{
int limit = floor(sqrt(n)) + 1;
vector<int> prime;
simpleSieve(limit, prime);
int low = limit;
int high = 2 * limit;
while (low < n)
{
if (high >= n)
high = n;
bool mark[limit + 1];
memset(mark, true, sizeof(mark));
for (int i = 0; i < prime.size(); i++)
{
int loLim = floor(low / prime[i]) * prime[i];
if (loLim < low)
loLim += prime[i];
for (int j = loLim; j < high; j += prime[i])
mark[j - low] = false;
}
for (int i = low; i < high; i++)
if (mark[i - low] == true)
cout << i << " ";
low = low + limit;
high = high + limit;
}
}
int main()
{
int n = 100;
cout << "Primes smaller than " << n << ":n";
segmentedSieve(n);
return 0;
}