Skip to content

Instantly share code, notes, and snippets.

@Chillee
Created April 13, 2019 04:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chillee/f6ced381737f761531894d0ccf34a5bf to your computer and use it in GitHub Desktop.
Save Chillee/f6ced381737f761531894d0ccf34a5bf to your computer and use it in GitHub Desktop.
Chinese Remainder Theorem
ll chinese(ll a, ll m, ll b, ll n) { //x = a %m, x = b%n, gcd(m,n)=1
ll x, y;
euclid(m, n, x, y);
ll ret = a * (y + m) % m * n + b * (x + n) % n * m;
if (ret >= m * n)
ret -= m * n;
return ret;
}
ll chinese_common(ll a, ll m, ll b, ll n) { // gcd(m,n) != 1
ll d = __gcd(m, n);
if (((b -= a) %= n) < 0)
b += n;
if (b % d)
return -1; // No solution
return d * chinese(ll(0), m / d, b / d, n / d) + a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment