#include using namespace std; int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { q = a / m; t = m; m = a % m, a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1; } int main() { int b0, c0, b1, c1; scanf("%d %d %d %d", &b0, &c0, &b1, &c1); while (c0 < 0) c0 += b0; while (c1 < 0) c1 += b1; if (abs(c1 - c0) % __gcd(b1, b0) != 0) cout << "NaN"; else { int res = (c0 * b1 * inv(b1, b0) + c1 * b0 * inv(b0, b1)) % (b0 * b1); cout << res; } return 0; }