-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime.ixx
84 lines (74 loc) · 1.59 KB
/
prime.ixx
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
module;
#include <string>
#include <sstream>
#include <vector>
export module prime;
namespace prime {
namespace {
constexpr int MAXN = 10000;
int spf[MAXN];
bool spf_filled = false;
void sieve()
{
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2) {
spf[i] = 2;
}
for (int i = 3; (i * i) < MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i) {
// marking spf[j] if it is not
// previously marked
if (spf[j] == j) {
spf[j] = i;
}
}
}
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
export inline [[nodiscard]]
std::vector<int> get_factorization(int x)
{
if (!spf_filled) {
sieve();
spf_filled = true;
}
std::vector<int> ret;
while (x != 1)
{
ret.push_back(spf[x]);
x = x / spf[x];
}
return ret;
}
export inline [[nodiscard]]
std::string vector_to_string(const std::vector<int>& a) {
std::stringstream result;
const int size = static_cast<int>(a.size());
for (const int p : {2, 3, 5, 7, 11, 13}) {
int count = 0;
for (int i = 0; i < size; ++i) {
if (a[i] == p) {
count++;
}
}
if (count > 0) {
result << p << "^" << count << " + ";
}
}
return result.str().substr(0, result.str().length() - 3);
}
}