LIPH's C++ Codes
prime_sieve.h
Go to the documentation of this file.
1#ifndef LIPH_PRIME_SIEVE_H_
2#define LIPH_PRIME_SIEVE_H_
3
4#include <cassert>
5#include <cstring>
6#include <string>
7
8namespace liph {
9
11public:
12 static const int max_size = 8 * 1024 * 1024; // 8388608, 1MB
13 prime_sieve(int max = 0) : max_(std::min(max, max_size)) { init(); }
14
15 ~prime_sieve() { delete[] bits_; }
16
17 bool is_prime(int n) {
18 if (n < 2) return false;
19 if (n <= max_) return get_bit(n);
20 if (n <= max_size) {
21 max_ = n;
22 init();
23 return is_prime(n);
24 }
25 return is_prime_loop(n);
26 }
27
28private:
29 void init() {
30 if (bits_) delete[] bits_;
31 if (max_ <= 0) return;
32 bits_ = new char[max_ / 8 + 1];
33 memset(bits_, -1, max_ / 8 + 1);
34 for (int i = 2; i <= max_; i++) {
35 if (get_bit(i)) {
36 for (int j = i + i; j <= max_; j += i) {
37 set_bit_false(j);
38 }
39 }
40 }
41 }
42
43 bool is_prime_loop(int n) const {
44 assert(n > max_size);
45 for (int i = 2; i * i <= n; i++) {
46 if (n % i == 0) return false;
47 }
48 return true;
49 }
50
51 void set_bit_false(int n) {
52 assert(n <= max_);
53 n -= 2;
54 char& ch = bits_[n / 8];
55 ch &= ~(1 << (7 - n % 8));
56 }
57
58 bool get_bit(int n) const {
59 assert(n <= max_);
60 n -= 2;
61 char ch = bits_[n / 8];
62 return ch & (1 << (7 - n % 8));
63 }
64
65 std::string debug_string() const {
66 std::string str;
67 int i = 1;
68 while (i <= max_) {
69 str += get_bit(i++) ? '1' : '0';
70 }
71 return str;
72 }
73
74private:
75 int max_{0};
76 char *bits_{nullptr};
77};
78
79} // namespace liph
80
81#endif // LIPH_PRIME_SIEVE_H_
Definition: prime_sieve.h:10
static const int max_size
Definition: prime_sieve.h:12
~prime_sieve()
Definition: prime_sieve.h:15
bool is_prime(int n)
Definition: prime_sieve.h:17
prime_sieve(int max=0)
Definition: prime_sieve.h:13
Definition: algorithm.h:10