-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprimes.hpp
69 lines (57 loc) · 1.12 KB
/
primes.hpp
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
// This file is covered by the LICENSE file in the root of this project.
#pragma once
#include <cassert>
#include <cmath>
#include <cstddef>
#include <utility>
#include <vector>
template<typename T>
T get_smallest_factor(T x)
{
if (x % 2 == 0)
return 2;
const auto sqrt_x = static_cast<T>(std::sqrt(x));
for (T i = 3; i <= sqrt_x; i += 2)
if (x % i == 0)
return i;
return x;
}
template<typename T>
bool is_prime(T x)
{
if (x <= 3)
return x >= 2;
else
return get_smallest_factor(x) == x;
}
template<typename T>
std::vector<std::pair<T, unsigned int>> factorize(T x)
{
assert(x > 1);
std::vector<std::pair<T, unsigned int>> factors;
while (x > 1)
{
const auto base = get_smallest_factor(x);
unsigned int exp = 0;
do
{
x /= base;
++exp;
} while (x % base == 0);
factors.push_back({base, exp});
}
return factors;
}
template<typename T>
std::vector<T> generate_primes(T max)
{
std::vector<T> primes;
if (max < 2)
return primes;
primes.push_back(2);
const auto is_prime = generate_prime_flags(max);
for (T i = 3; i <= max; i += 2)
if (is_prime[i])
primes.push_back(i);
return primes;
}