Skip to content

Commit

Permalink
Update exgcd
Browse files Browse the repository at this point in the history
  • Loading branch information
OmeletWithoutEgg committed Apr 4, 2024
1 parent 24da0b3 commit ab87be6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
14 changes: 7 additions & 7 deletions codes/Math/ChineseRemainder.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// please ensure r_i\in[0,m_i)
bool crt(lld &m1, lld &r1, lld m2, lld r2) {
if (m2 > m1) swap(m1, m2), swap(r1, r2);
lld g, a, b; exgcd(m1, m2, g, a, b);
if ((r2 - r1) % g != 0) return false;
m2 /= g; lld D = (r2 - r1) / g % m2 * a % m2;
r1 += (D < 0 ? D + m2 : D) * m1; m1 *= m2;
assert (r1 >= 0 && r1 < m1);
return true;
if (m2 > m1) swap(m1, m2), swap(r1, r2);
auto [g, a, b] = exgcd(m1, m2);
if ((r2 - r1) % g != 0) return false;
m2 /= g; lld D = (r2 - r1) / g % m2 * a % m2;
r1 += (D < 0 ? D + m2 : D) * m1; m1 *= m2;
assert (r1 >= 0 && r1 < m1);
return true;
}
7 changes: 4 additions & 3 deletions codes/Math/ExtendedGCD.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// ax+ny = 1, ax+ny == ax == 1 (mod n)
void exgcd(lld x, lld y, lld &g, lld &a, lld &b) {
if (y == 0) g = x, a = 1, b = 0;
else exgcd(y, x % y, g, b, a), b -= (x / y) * a;
tuple<lld,lld,lld> exgcd(lld x, lld y) {
if (y == 0) return {x, 1, 0};
auto [g, b, a] = exgcd(y, x % y);
return {g, a, b - (x / y) * a};
}

0 comments on commit ab87be6

Please sign in to comment.