Created
April 13, 2019 04:18
-
-
Save Chillee/f6ced381737f761531894d0ccf34a5bf to your computer and use it in GitHub Desktop.
Chinese Remainder Theorem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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