以前不会解二元一次不定方程的时候不会做,现在会做了。
#include <cstdio>
#include <cassert>
using namespace std;
typedef __int64 int64;
void solveType1(int64 a, int64 b, int64 & x, int64 & y, int64 & d) {
if (b == 0) {
x = 1; y = 0; d = a;
return;
}
int64 _x, _y, _d;
solveType1(b, a % b, _x, _y, _d);
x = _y;
y = _x - _y * ((a - a % b) / b);
d = _d;
}
bool solveType2(int64 a, int64 b, int64 c, int64 & x, int64 & y, int64 & d) {
int64 _x, _y, _d;
solveType1(a, b, _x, _y, _d);
// assert(a * _x + b * _y == _d);
if (c % _d != 0) return false;
int64 n = c / _d;
x = n * _x;
y = n * _y;
d = _d;
return true;
}
inline int64 getSign(int64 x) { return x < 0 ? -1 : 1; }
inline int64 iabs(int64 x) { return x < 0 ? -x : x; }
bool solveType3(int64 a, int64 b, int64 c, int64 & x, int64 & y, int64 & d) {
if (c < 0) { a = -a; b = -b; c = -c; }
int64 sa = getSign(a);
int64 sb = getSign(b);
int64 _x, _y, _d;
if (!solveType2(a * sa, b * sb, c, _x, _y, _d)) return false;
// assert(a * sa * _x + b * sb * _y == c);
x = sa * _x;
y = sb * _y;
d = _d;
return true;
}
int64 solve(int64 x, int64 y, int64 m, int64 n, int64 L) {
int64 t, k, _d;
if (!solveType3(n - m, L, x - y, t, k, _d)) return -1;
// assert((n - m) * t + L * k == x - y);
// printf("*** %I64d %I64d %I64d\n", t, k, _d);
int64 dx = iabs(L / _d);
if (t == 0) return 0;
if (t > 0) return t % dx;
if (t < 0) return (dx - ((-t) % dx)) % dx;
}
int main() {
int64 x, y, m, n, L;
scanf("%I64d %I64d %I64d %I64d %I64d", &x, &y, &m, &n, &L);
int64 ans = solve(x, y, m, n, L);
if (ans == -1) printf("Impossible\n");
else printf("%I64d\n", ans);
return 0;
}