Skip to content

Commit 84d2b11

Browse files
committed
Speedup factorize
1 parent 1a2c526 commit 84d2b11

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

cp-algo/algebra/number_theory.hpp

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,29 +58,36 @@ namespace cp_algo::algebra {
5858
// https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
5959
void factorize(uint64_t m, std::vector<int64_t> &res) {
6060
if(m % 2 == 0) {
61-
res.push_back(2);
6261
factorize(m / 2, res);
62+
res.push_back(2);
6363
} else if(is_prime(m)) {
6464
res.push_back(m);
6565
} else if(m > 1) {
66-
uint64_t g = 1;
6766
using base = dynamic_modint;
6867
base::with_switched_mod(m, [&]() {
69-
while(g == 1 || g == m) {
70-
auto f = [t = random::rng()](auto x) {
71-
return x * x + t;
72-
};
73-
g = 1;
74-
base x, y;
75-
while(g == 1) {
68+
base t = random::rng();
69+
auto f = [&](auto x) {
70+
return x * x + t;
71+
};
72+
base x, y;
73+
base g = 1;
74+
while(g == 1) {
75+
for(int i = 0; i < 64; i++) {
7676
x = f(x);
7777
y = f(f(y));
78-
g = std::gcd(m, (x - y).getr());
78+
if(x == y) [[unlikely]] {
79+
t = random::rng();
80+
x = y = 0;
81+
} else {
82+
base t = g * (x - y);
83+
g = t == 0 ? g : t;
84+
}
7985
}
86+
g = std::gcd(g.getr(), m);
8087
}
88+
factorize(g.getr(), res);
89+
factorize(m / g.getr(), res);
8190
});
82-
factorize(g, res);
83-
factorize(m / g, res);
8491
}
8592
}
8693
auto factorize(int64_t m) {

0 commit comments

Comments
 (0)