#include using namespace std; using ll = long long; // 負の数にも対応したmod inline ll mod(ll a, ll m) { return (a % m + m) % m; } // 拡張ユークリッドの互除法 // ax + by = gcd(a, b)を満たす(x, y)を計算。gcd(a, b)を返す ll ext_gcd(ll a, ll b, ll& x, ll& y) { if(b == 0) { x = 1; y = 0; return a; } ll d = ext_gcd(b, a%b, y, x); y -= a/b * x; return d; } // ax=1(mod m)となるxを返す。解なしだと-1を返す ll mod_inv(ll a, ll m) { ll x, y, d; d = ext_gcd(a, m, x, y); if(d == 1) return mod(x, m); else return -1; } // 中国剰余定理 // x=B (mod M)となる(r, m)を返す // 解なしの場合は(0, -1)を返す pair chinese_rem(const vector& B, const vector& M) { ll x = 0, m = 1; for(int i = 0; i < (int)B.size(); ++i) { ll p, q; ll d = ext_gcd(m, M[i], p, q); //pは M/d (mod m[i]/d) の逆元 if((B[i] - x) % d != 0) return {0, -1}; ll t = (B[i] - x) / d * p % (M[i] / d); x += m * t; m *= M[i] / d; } return {mod(x, m), m}; } // Ax=B (mod M)を解く pair linear_congruence(const vector& A, const vector& B, const vector& M) { ll x = 0, m = 1; for(int i = 0; i < (int)A.size(); ++i) { ll a = A[i] * m; ll b = B[i] - A[i] * x; ll d = __gcd(M[i], a); if(b % d != 0) return {0, -1}; ll t = b / d * mod_inv(a / d, M[i] / d) % (M[i] / d); x = x + m * t; m *= M[i] / d; } return {mod(x, m), m}; } // https://yukicoder.me/problems/447 int main() { vector B(3), M(3); for(int i = 0; i < 3; ++i) cin >> B[i] >> M[i]; pair p = chinese_rem(B, M); if(p.second == -1) { // 解なし cout << -1 << endl; return 0; } ll ans = p.first; if(ans == 0) ans += p.second; cout << ans << endl; }