B_0, C_0 = map(int, input().split()) C_0 = C_0 % B_0 if C_0 >= 0 else (B_0 - (-C_0) % B_0) % B_0 B_1, C_1 = map(int, input().split()) C_1 = C_1 % B_1 if C_1 >= 0 else (B_1 - (-C_1) % B_1) % B_1 A = [[1, 0], [0, 1]] B = [B_0, B_1] i_0 = 0 if B_0 >= B_1 else 1 i_1 = 1 - i_0 while B[i_1] != 0: q = B[i_0] // B[i_1] A[i_0][i_0] -= q * A[i_1][i_0] A[i_0][i_1] -= q * A[i_1][i_1] B[i_0] %= B[i_1] i_0, i_1 = i_1, i_0 gcd = B[i_0] c = C_0 % gcd if C_1 % gcd != c: print("NaN") quit() lcm = (B_0 // gcd) * B_1 answer = c + A[i_0][0] * B_0 * ((C_1 - c) // gcd) + A[i_0][1] * B_1 * ((C_0 - c) // gcd) answer = answer % lcm if answer >= 0 else (lcm - (-answer) % lcm) % lcm print(answer)