#!/usr/bin/env python3 # %% import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines # %% m = map(int, read().split()) XY = zip(m, m) X, Y = zip(*XY) # %% class NotFoundError(Exception): pass def extgcd(a, b): """return x,y,d such that ax + by = d > 0""" x, y, u, v, s, t = 1, 0, 0, 1, a, b while t: k = s // t s, t = t, s - k * t x, u = u, x - k * u y, v = v, y - k * v return x, y, s def CRT(a, n, b, m): """find (c, mod) where x = a (n), x = b (m) iff x = c (mod)""" p, q, d = extgcd(n, m) if (a - b) % d != 0: raise NotFoundError mod = n * (m // d) a += n * ((b - a) // d * p % (m // d)) return a, mod # %% x, n = 0, 1 for y, m in zip(X, Y): try: x, n = CRT(x, n, y, m) except NotFoundError: print(-1) exit() x %= n if not x: x = n print(x)