#include using namespace std; int64_t extendedGcd(int64_t a, int64_t b, int64_t& x, int64_t& y) { if (b == 0) { x = 1; y = 0; return a; } else { const int64_t g = extendedGcd(b, a % b, y, x); y -= (a / b) * x; return g; } } int main() { int64_t B0, C0, B1, C1; cin >> B0 >> C0 >> B1 >> C1; const int64_t g = gcd(B0, B1); if (g != 1) { cout << "NaN" << endl; return 0; } (C0 += B0 * (abs(C0) / B0 + 1)) %= B0; (C1 += B1 * (abs(C1) / B1 + 1)) %= B1; int64_t p, q; extendedGcd(B0, B1, p, q); int64_t x = C0 * q * B1 + C1 * p * B0; if (x < 0) { x += B0 * B1; } assert(x % B0 == C0); assert(x % B1 == C1); cout << x << endl; }