import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys import time from collections import Counter,deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines write=sys.stdout.write def Extended_Euclid(n,m): stack=[] while m: stack.append((n,m)) n,m=m,n%m if n>=0: x,y=1,0 else: x,y=-1,0 for i in range(len(stack)-1,-1,-1): n,m=stack[i] x,y=y,x-(n//m)*y return x,y def LCM(n,m): if n or m: return abs(n)*abs(m)//math.gcd(n,m) return 0 def CRT(remainder_lst,mod_lst): assert len(remainder_lst)==len(mod_lst) if not remainder_lst: return 0,1 remainder,mod=remainder_lst[0],mod_lst[0] for r,m in zip(remainder_lst[1:],mod_lst[1:]): if (r,m)==(-1,0): remainder,mod=-1,0 break r%=m g=math.gcd(mod,m) lcm=LCM(mod,m) if remainder%g!=r%g: remainder,mod=-1,0 break remainder,mod=(r+m*((remainder-r)//g)*Extended_Euclid(m//g,mod//g)[0])%lcm,lcm return remainder,mod R,M=[],[] for _ in range(2): m,r=map(int,readline().split()) R.append(r) M.append(m) r,m=CRT(R,M) if r==-1: ans="NaN" else: ans=r print(ans)