传送门: POJ 1061
题解
同余方程解法
注意取模时, 不能被整除的模数, 可能结果为负, 所以尽量使扩展欧几里得的a, b为正值
AC code:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL px, py, m, n, L, x, y, f;
LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a;}
void expgcd(LL a, LL b, LL &x, LL &y, LL c) {
if (!b) {
if (c % a == 0) {
x = c / a;
y = 0;
}
else {
f = 0;
}
return;
}
expgcd(b, a % b, y, x, c);
if (!f) return;
y -= a / b * x;
}
void swap(LL *x, LL *y) {
LL t = *x;
*x = *y;
*y = t;
}
int main() {
//freopen("in.txt", "r", stdin);
while (cin >> px >> py >> m >> n >> L) {
f = 1;
if (m < n) {
swap(&m, &n);
swap(&px, &py);
}
expgcd(m - n, L, x, y, py - px);
//cout << x << endl;
if (!f) cout << "Impossible" << endl;
else {
x %= L;
if (x < 0) x += L;
cout << x << endl;
}
}
return 0;
}