def ext_gcd(a, b): if b == 0: return (a, 1, 0) else: g, x, y = ext_gcd(b, a % b) return (g, y, x - (a // b) * y) def chinese_rem(b1, m1, b2, m2): d, x, _ = ext_gcd(m1, m2) if (b2 - b1) % d != 0: return (None, None) else: m = m1 * (m2 // d) t = ((b2 - b1) // d * x) % (m2 // d) r = (b1 + m1 * t) % m return (r, m) r, m = map(int, input().split()) for _ in range(2): x, y = map(int, input().split()) nr, nm = chinese_rem(r, m, x, y) if nr is None: print("-1") exit() else: r, m = nr, nm print(r)