Skip to content

Commit de44796

Browse files
committed
co-routines in factorize
1 parent f657ad8 commit de44796

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

cp-algo/number_theory/factorize.hpp

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,18 @@
22
#define CP_ALGO_MATH_FACTORIZE_HPP
33
#include "primality.hpp"
44
#include "../random/rng.hpp"
5+
#include <generator>
56
namespace cp_algo::math {
67
// https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
7-
std::basic_string<uint64_t> factorize(uint64_t m) {
8+
std::generator<uint64_t> factorize(uint64_t m) {
89
if(m % 2 == 0) {
9-
return factorize(m / 2) + (uint64_t)2;
10+
co_yield std::ranges::elements_of(factorize(m / 2));
11+
co_yield 2;
1012
} else if(is_prime(m)) {
11-
return {m};
13+
co_yield m;
1214
} else if(m > 1) {
1315
using base = dynamic_modint<int64_t>;
14-
return base::with_mod(m, [&]() {
16+
auto g = base::with_mod(m, [&]() {
1517
base t = random::rng();
1618
auto f = [&](auto x) {
1719
return x * x + t;
@@ -32,10 +34,10 @@ namespace cp_algo::math {
3234
}
3335
g = std::gcd(g.getr(), m);
3436
}
35-
return factorize(g.getr()) + factorize(m / g.getr());
37+
return g.getr();
3638
});
37-
} else {
38-
return {};
39+
co_yield std::ranges::elements_of(factorize(g));
40+
co_yield std::ranges::elements_of(factorize(m / g));
3941
}
4042
}
4143
}

verify/number_theory/factorize.test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ using namespace cp_algo::math;
1010
void solve() {
1111
int64_t m;
1212
cin >> m;
13-
auto res = factorize(m);
13+
auto res = to<vector>(factorize(m));
1414
ranges::sort(res);
1515
cout << size(res) << " ";
1616
ranges::copy(res, ostream_iterator<int64_t>(cout, " "));

0 commit comments

Comments
 (0)