Skip to content

Commit 9e2f850

Browse files
committed
Added wheel factorization
1 parent e2aeace commit 9e2f850

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

math/compute_wheel.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
vector<int> compute_wheel(vector<int> const& v) {
6+
int sz = 1;
7+
for (auto x : v) sz *= x;
8+
9+
vector<int> primes;
10+
11+
vector<char> s(sz+1);
12+
for (auto i : v)
13+
for (int j = i; j <= sz; j += i)
14+
s[j] = 1;
15+
16+
for (int i = v.back(); i <= sz; i++)
17+
if (!s[i])
18+
primes.push_back(i);
19+
20+
primes.push_back(sz+1);
21+
primes.push_back(primes.front()+sz);
22+
vector<int> inc(primes.size()-1);
23+
24+
for (int i = 0; i < int(inc.size()); i++)
25+
inc[i] = primes[i+1]-primes[i];
26+
27+
return inc;
28+
}
29+
30+
int main() {
31+
auto x = compute_wheel({2, 3, 5});
32+
33+
cout << "{ ";
34+
for (auto i : x) cout << i << ", ";
35+
cout << "}\n";
36+
}

math/wheel_factorization.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <bits/stdc++.h>
2+
3+
#pragma GCC optimize("O3")
4+
5+
using namespace std;
6+
7+
using ll = uint64_t;
8+
9+
template <typename T, int sz>
10+
int tam(T(&)[sz]) {
11+
return sz;
12+
}
13+
14+
vector<ll> factor(ll x) {
15+
static const int primes[] = {2, 3, 5};
16+
static const int inc[] = { 4, 2, 4, 2, 4, 6, 2, 6 };
17+
// see compute_wheel.cpp to compute the wheel efficiently
18+
19+
vector<ll> factors;
20+
21+
for (auto p : primes)
22+
while (x%p == 0) x /= p, factors.push_back(p);
23+
24+
ll k = 7, i = 0;
25+
26+
while (k*k <= x) {
27+
while (x%k == 0)
28+
x /= k, factors.push_back(k);
29+
k += inc[i++];
30+
if (i == tam(inc)) i = 0;
31+
}
32+
33+
factors.push_back(x);
34+
sort(factors.begin(), factors.end());
35+
return factors;
36+
}
37+
38+
int main() {
39+
ll x;
40+
cin >> x;
41+
42+
auto ans = factor(x);
43+
44+
for (auto p : ans) cout << p << " ";
45+
cout << "\n";
46+
}

0 commit comments

Comments
 (0)