import math def Chinese_Surplus_Theorem(b1,b2,m1,m2): def Euclidean_Algorithm(a,b,d): a,b = max(a,b),min(a,b) if a == d and b == 0: return 1,0 div,mod = divmod(a,b) nx,ny = Euclidean_Algorithm(b,mod,d) res = (ny,nx - div*ny) return res d = math.gcd(m1,m2) if m1 < m2: m1,m2 = m2,m1 b1,b2 = b2,b1 if b1 % d != b2 % d:return 0,0 p,q = Euclidean_Algorithm(m1,m2,d) s = (b2-b1)//d return (b1 + s*m1*p) % (m1*m2//d) ,m1*m2//d b0,c0 = map(int,input().split()) b1,c1 = map(int,input().split()) # c0 %= b0 # c1 %= b1 x,y = Chinese_Surplus_Theorem(c0,c1,b0,b1) if x == y == 0: print("NaN") else: print(x)