1
0
Fork 0

Update exgcd.cc

This commit is contained in:
Ariel 2024-03-06 13:23:19 +08:00 committed by GitHub
parent a7fc899de6
commit 74e7a1d5d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 17 additions and 0 deletions

View File

@ -1,3 +1,4 @@
namespace Exgcd { namespace Exgcd {
struct exgcd_solution_t { struct exgcd_solution_t {
ll x, y, gcd; ll x, y, gcd;
@ -34,6 +35,22 @@ namespace Exgcd {
} }
} }
// solve { x = a_i (mod n_i) } if n_i's are coprime
optional<ll> crt(const vector<pll>& equations) {
ll prod = 1;
for (auto&& [a, n] : equations) {
prod *= n;
}
ll res = 0;
for (auto&& [a, n] : equations) {
ll m = prod / n;
auto m_rev = inverse(m, n);
if (m_rev == nullopt) return nullopt;
res = mod(res + a * mod(m * m_rev.value(), prod), prod);
}
return res;
}
// find minimal non-negative integral solutions of `ax + by = c` // find minimal non-negative integral solutions of `ax + by = c`
optional<diophantine_solution_t> diophantine(ll a, ll b, ll c, bool force_positive = false) { optional<diophantine_solution_t> diophantine(ll a, ll b, ll c, bool force_positive = false) {
if (a < 0 || b < 0 || a == 0 && b == 0) return nullopt; if (a < 0 || b < 0 || a == 0 && b == 0) return nullopt;