def ext_gcd(a, b): """ 一次不定方程式 ax + by = d(=gcd(a, b))の特殊解を求める :return: x, y, gcd(a, b)をタプルで返す """ # a * x + b * y == d ret_x, ret_y, ret_gcd = 1, 0, a x2, y2, d2 = 0, 1, b while d2 != 0: q = ret_gcd // d2 ret_gcd, d2 = d2, ret_gcd - d2 * q ret_x, x2 = x2, ret_x - x2 * q ret_y, y2 = y2, ret_y - y2 * q if ret_gcd < 0: ret_gcd, ret_x, ret_y = -ret_gcd, -ret_x, -ret_y return ret_x, ret_y, ret_gcd def calc_inv(a, m): """ ax ≡ 1 (mod m)のx(a^(-1))の値を求める :return: gcd(a, m), """ inv, _, g = ext_gcd(a, m) return g, (inv + m) % m def Chinese_Remainder_Theorem(r: list, m: list): """ # x ≡ r_i (mod m_i) (0<=i<=n)を満たす連立合同式の解x (mod m0)があれば(x, m0)を返す # 解が存在しない場合は(None, None)が返る :return: """ n = len(r) r0, m0 = 0, 1 for i in range(n): assert 1 <= m[i] r1 = r[i] % m[i] m1 = m[i] if m0 < m1: r0, r1 = r1, r0 m0, m1 = m1, m0 if m0 % m1 == 0: if r0 % m1 != r1: return None, None continue g, im = calc_inv(m0, m1) u1 = m1 // g if (r1 - r0) % g: return None, None x = (r1 - r0) // g % u1 * im % u1 r0 += x * m0 m0 *= u1 if r0 < 0: r0 += m0 return r0, m0 X = [] Y = [] for i in range(3): x, y = map(int, input().split()) X.append(x) Y.append(y) ans, m = Chinese_Remainder_Theorem(X, Y) print(ans if ans is not None else -1)