#include using namespace std; #define rep(i,n) for(int i = 0; i < (int)(n); ++i) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; --i) #define ALL(a) a.begin(), a.end() #define Sort(a) sort(a.begin(), a.end()) #define RSort(a) sort(a.rbegin(), a.rend()) typedef long long int ll; typedef long double ld; typedef vector vi; typedef vector vll; typedef vector vc; typedef vector vst; typedef vector vd; typedef pair P; const long long INF = 0x1fffffffffffffff; const long long MOD = 998244353; const long double PI = acos(-1); template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template inline T vin(T& vec, U n) { vec.resize(n); for(int i = 0; i < (int) n; ++i) cin >> vec[i]; return vec; } template inline void vout(T vec, string s = "\n"){ for(auto x : vec) cout << x << s; } template void in(T&... a){ (cin >> ... >> a); } void out(){ cout << '\n'; } template void out(const T& a, const Ts&... b){ cout << a; (cout << ... << (cout << ' ', b)); cout << '\n'; } template void inGraph(vector>& G, U n, U m, bool directed = false){ G.resize(n); for(int i = 0; i < m; i++){ int a, b; cin >> a >> b; a--, b--; G[a].push_back(b); if(!directed) G[b].push_back(a); } } namespace CRT{ long long extGCD(long long a, long long b, long long &x, long long &y){ if(b == 0){ x = 1; y = 0; return a; } long long d = extGCD(b, a % b, y, x); y -= a / b * x; return d; } pair ChineseRem(const vector &b, const vector &m) { long long r = 0, M = 1; for(int i = 0; i < (int) b.size(); i++){ long long p, q; long long d = extGCD(M, m[i], p, q); if((b[i] - r) % d != 0) return {0, -1}; long long tmp = (b[i] - r) / d * p % (m[i] / d); r += M * tmp; M *= m[i] / d; } r %= M; if(r < 0) r += M; return {r, M}; } } ll b0, c0, b1, c1; void input(){ in(b0, c0, b1, c1); } void solve(){ pair p = CRT::ChineseRem({c0, c1}, {b0, b1}); if(p.second == -1){ cout << "NaN" << endl; }else if(c0 == 0 && c1 == 0){ cout << p.second << endl; }else{ cout << p.first << endl; } } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); input(); solve(); }