// हर हर महादेव #include using namespace std; template T inv(T a, T m) { T u = 0, v = 1; T old = m; while (a != 0) { T t = m / a; m -= t * a; swap(a, m); u -= t * v; swap(u, v); } assert(m == 1); if(u < 0){ u += old; } return u; } // x == a[i] mod m[i] int crt(vector a,vector m){ int n = a.size(); int prod = 1; vector M(n); vector y(n); for(int i = 0; i < n; i++){ prod *= m[i]; } for(int i = 0; i < n; i++){ M[i] = prod / m[i]; if(__gcd(M[i],m[i]) != 1){ return -1; } y[i] = inv(M[i],m[i]); } int x = 0; for(int i = 0; i < n; i++){ (x += a[i] * y[i] * M[i]) %= prod; } return x; } int main(){ ios::sync_with_stdio(false);cin.tie(0); vector a(2),m(2); for(int i = 0; i < 2; i++){ cin >> m[i] >> a[i]; if(a[i] < 0){ a[i] += m[i]; } } int ans = crt(a,m); if(ans == -1){ cout << "NaN"; } else{ cout << ans; } return 0; }