diff --git a/number/exgcd.cc b/number/exgcd.cc index fdda090..4ca819e 100644 --- a/number/exgcd.cc +++ b/number/exgcd.cc @@ -1,3 +1,4 @@ + namespace Exgcd { struct exgcd_solution_t { ll x, y, gcd; @@ -34,6 +35,22 @@ namespace Exgcd { } } + // solve { x = a_i (mod n_i) } if n_i's are coprime + optional crt(const vector& 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` optional diophantine(ll a, ll b, ll c, bool force_positive = false) { if (a < 0 || b < 0 || a == 0 && b == 0) return nullopt;