-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrimeSieve.h
104 lines (89 loc) · 2.8 KB
/
PrimeSieve.h
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once
#include <algorithm>
#include <concepts>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <memory>
#include <vector>
#include "BitArray.h"
// An Eratosthenes prime sieve.
template<std::unsigned_integral T>
class PrimeSieve
{
private:
// The underlying bit array.
BitArray sieve;
// The exclusive upper bound on the numbers sieved.
T limit;
// The primes in [0, 'limit').
std::shared_ptr<std::vector<T>> primes;
public:
// Constructs a PrimeSieve over [0, 'limit') and optionally outputs progress to 'clog'.
PrimeSieve (T limit, bool verbose = false)
: limit (limit),
sieve (limit, true),
primes (std::make_shared<std::vector<T>> ())
{
// Standard Eratosthenes sieve algorithm.
sieve.Reset (0);
sieve.Reset (1);
T prime = 2;
primes->emplace_back (2);
if (verbose)
while (prime * prime < limit)
{
std::clog << "Striking out multiples of " << prime << "\n";
for (T i = prime * prime; i < limit; i += prime)
sieve.Reset (i);
for (T i = prime + 1; ; ++i)
if (sieve.Get (i))
{
prime = i;
primes->emplace_back (i);
break;
}
}
else
while (prime * prime < limit)
{
for (T i = prime * prime; i < limit; i += prime)
sieve.Reset (i);
for (T i = prime + 1; ; ++i)
if (sieve.Get (i))
{
prime = i;
primes->emplace_back (i);
break;
}
}
for (T i = prime + 1; i < limit; ++i)
if (sieve.Get (i))
primes->emplace_back (i);
}
// Returns the primes in [0, 'limit').
std::shared_ptr<const std::vector<T>> Primes () const
{
return primes;
}
// Returns the number of primes in [0, 'limit').
std::size_t Count () const
{
return primes->size ();
}
// Returns the number of primes in [0, 'n'], if 'n' is in [0, 'limit').
// Out of range arguments result in undefined behaviour.
std::size_t PrimePi (T n) const
{
// Find the first prime which exceeds 'n'.
auto nextPrime = std::upper_bound (primes->cbegin (), primes->cend (), n);
// Return the index of the prime just discovered.
return std::distance (primes->cbegin (), nextPrime);
}
// Returns whether 'n' is prime, if 'n' is in [0, 'limit').
// Out of range arguments result in undefined behaviour.
bool IsPrime (T n) const
{
return sieve.Get (n);
}
};