0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-09-16 20:05:26 +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;
const char endl = '\n';
const int N = 1e5 + 5;
int n;
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) {
x = 1;
y = 0;
x = 1, y = 0;
return a;
}
long long g = exgcd(b, a % b, y, x);
y -= a / b * x;
return g;
}
long long lcm(long long a, long long b) {
return a / std::__gcd(a, b) * b;
y -= a / b * x;
return g;
}
int main() {
@ -33,18 +29,17 @@ int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
// $x \equiv a_i (mod b_i)$
cin >> a2 >> b2;
cin >> b2 >> a2;
if (i == 1) {
a1 = a2;
b1 = b2;
a1 = a2;
} else {
long long x, y,
g = exgcd(a1, a2, x, y),
c = b2 - b1,
m1 = a2 / g,
m2 = lcm(a1, a2);
g = exgcd(b1, b2, x, y),
c = a2 - a1,
m1 = b2 / g,
m2 = b1 / g * b2;
if (c % g) {
cout << -1 << endl;
@ -52,13 +47,13 @@ int main() {
exit(0);
}
x = (static_cast<__int128>(x) * c / g % m1 + m1) % m1;
b1 = ((a1 * x + b1) % m2 + m2) % m2;
a1 = m2;
x = static_cast<__int128>(x) * c / g % m1;
a1 = ((a1 + b1 * x) % m2 + m2) % m2;
b1 = m2;
}
}
cout << b1 % a1 << endl;
cout << a1 % b1 << endl;
return 0;
}