0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-23 23:08:47 +00:00

P4777 【模板】扩展中国剩余定理(EXCRT)

https://www.luogu.com.cn/record/92007494
This commit is contained in:
Baoshuo Ren 2022-10-29 11:22:01 +08:00
parent 719bb0ec83
commit 017a3770b3
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

View File

@ -5,25 +5,21 @@ using std::cin;
using std::cout; using std::cout;
const char endl = '\n'; const char endl = '\n';
const int N = 1e5 + 5;
int n; int n;
long long a1, b1, a2, b2; long long a1, b1, a2, b2;
long long exgcd(long long a, long long b, long long &x, long long &y) { long long exgcd(long long a, long long b, long long &x, long long &y) {
if (!b) { if (!b) {
x = 1; x = 1, y = 0;
y = 0;
return a; return a;
} }
long long g = exgcd(b, a % b, y, x); long long g = exgcd(b, a % b, y, x);
y -= a / b * x;
return g;
}
long long lcm(long long a, long long b) { y -= a / b * x;
return a / std::__gcd(a, b) * b;
return g;
} }
int main() { int main() {
@ -33,18 +29,17 @@ int main() {
cin >> n; cin >> n;
for (int i = 1; i <= n; i++) { for (int i = 1; i <= n; i++) {
// $x \equiv a_i (mod b_i)$ cin >> b2 >> a2;
cin >> a2 >> b2;
if (i == 1) { if (i == 1) {
a1 = a2;
b1 = b2; b1 = b2;
a1 = a2;
} else { } else {
long long x, y, long long x, y,
g = exgcd(a1, a2, x, y), g = exgcd(b1, b2, x, y),
c = b2 - b1, c = a2 - a1,
m1 = a2 / g, m1 = b2 / g,
m2 = lcm(a1, a2); m2 = b1 / g * b2;
if (c % g) { if (c % g) {
cout << -1 << endl; cout << -1 << endl;
@ -52,13 +47,13 @@ int main() {
exit(0); exit(0);
} }
x = (static_cast<__int128>(x) * c / g % m1 + m1) % m1; x = static_cast<__int128>(x) * c / g % m1;
b1 = ((a1 * x + b1) % m2 + m2) % m2; a1 = ((a1 + b1 * x) % m2 + m2) % m2;
a1 = m2; b1 = m2;
} }
} }
cout << b1 % a1 << endl; cout << a1 % b1 << endl;
return 0; return 0;
} }