#pragma GCC optimize("Ofast") #include using namespace std; #define rep(i, a, b) for (int i = a; i < (b); ++i) #define rrep(i, b, a) for (int i = b; i-- > (a);) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() using ll = long long; using ull = unsigned long long; using pii = pair; using vi = vector; template bool chmin(T& lhs, T rhs) { return lhs > rhs ? (lhs = rhs, true) : false; } template bool chmax(T& lhs, T rhs) { return lhs < rhs ? (lhs = rhs, true) : false; } struct IOIO { IOIO() { cin.tie(0)->sync_with_stdio(0); } } ioio; pair extgcd(ll a, ll b) { if (b == 0) return {1, 0}; auto [x, y] = extgcd(b, a % b); return {y, x - (a / b) * y}; } ll inv(ll x, ll m) { auto [res, _] = extgcd(x, m); return (res % m + m) % m; } ll garner(vector r, vector m) { int n = ssize(r); ll x = r[0] % m[0]; ll p = m[0]; rep(i, 1, n) { if (m[i] > p) swap(m[i], p), swap(r[i], x); if (p % m[i] == 0) { if (x % m[i] != r[i]) return -1; } else { ll g = gcd(p, m[i]); if ((r[i] - x) % g != 0) return -1; ll t = ((r[i] - x) / g) % (m[i] / g) * inv(p / g, m[i] / g) % (m[i] / g); x += p * t; p *= m[i] / g; x = (x % p + p) % p; } } return (x == 0 ? x + p : x); } int main() { int n = 3; vector r(n), m(n); rep(i, 0, n) cin >> r[i] >> m[i]; cout << garner(r, m) << '\n'; }