-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsieve.cpp
63 lines (63 loc) · 1.31 KB
/
sieve.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
/// Name: Sieve of Eratosthenes
/// Description:
/// Detail:
/// Guarantee: struct Sieve {
/// Dependencies:
/// Parent:
struct Sieve {
Sieve(int n):prime(n+1,true),fac(n+1,1){
prime[0] = prime[1] = false;
for (auto p=2; p<=n; ++p)
if (prime[p]) {
fac[p] = p;
for (auto j=2*p; j<=n; j+=p)
prime[j] = false, fac[j] = p;
}
}
vector<int> factor(int i) const {
auto ps = vector<int>();
while (i > 1)
ps.push_back(fac[i]), i /= fac[i];
return ps;
}
struct Count { int p, alpha; };
vector<Count> counts(int i) const {
auto fs = vector<Count>();
while (i > 1) {
auto p = fac[i];
auto l = 0;
while (fac[i] == p)
i /= p, ++l;
fs.push_back(Count{p, l});
}
return fs;
}
vector<int> uniqfacs(int i) const {
auto ps = vector<int>();
while (i > 1) {
ps.push_back(fac[i]);
while (ps.back() == fac[i])
i /= fac[i];
}
return ps;
}
vector<int> divisors(int i) const {
auto ds = vector<int>({1});
for (auto c : counts(i)) {
auto l = (int)ds.size();
for (auto k=0; k<c.alpha; ++k)
for (auto j=0; j<l; ++j)
ds.push_back(ds.rbegin()[l-1] * c.p);
}
return ds;
}
vector<int> allPrimes() const {
vector<int> ps;
for (auto p=2; p<(int)prime.size(); ++p)
if (prime[p])
ps.push_back(p);
return ps;
}
vector<bool> prime;
vector<int> fac;
};