#include #include #include #define LOG(FMT...) fprintf(stderr, FMT) int exgcd(int a, int b, int &x, int &y) { if (b) { int d = exgcd(b, a % b, y, x); y -= a / b * x; return d; } x = y = 1; return a; } int main() { int b1, c1, b2, c2; scanf("%d%d%d%d", &b1, &c1, &b2, &c2); int x, y, d; d = exgcd(b1, b2, x, y); if ((c1 - c2) % d) { puts("NaN"); } else { int t = (c1 - c2) / d; x *= t, y *= t; int g = b1 * b2 / d; int m = c2 + y * b2; int k = -m / g; if (k * g < -m) { k += 1; } printf("%d\n", k * g + m); } return 0; }