def extgcd(a, b): """ 拡張Euclidの互除法 INPUT: a, b OUTPUT: d: gcd(a, b) (x, y): ax + by = d の解 """ if b == 0: return a, 1, 0 d, y, x = extgcd(b, a % b) y -= a // b * x return d, x, y def crt(B, M): """ 中国剰余定理 x ≡ b0 (mod M0) x ≡ b1 (mod M1) x ≡ b2 (mod M2) となるxを求める INPUT: B:[b0,b1,..] M:[m0,m1,..] OUTPUT: (x, mod) -> x:最小の答え(0<=x 解がない場合 """ x = 0 mod = 1 for b, m in zip(B, M): d, p, _ = extgcd(mod, m) if (b - x) % d != 0: return 0, -1 x += (b - x) // d * p % (m // d) * mod mod *= m // d return x % mod, mod if __name__ == "__main__": bm = tuple(tuple(map(int, input().split())) for _ in range(3)) b, m = zip(*bm) x, mod = crt(b, m) if mod == -1: x = -1 print(x)