#include // #include // #include using namespace std; // using namespace atcoder; // using bint = boost::multiprecision::cpp_int; using ll = long long; using ull = unsigned long long; using ld = long double; using P = pair; using vi = vector; using vvi = vector; using vvvi = vector; using ve = vector>; using vb = vector; using vvb = vector; #define rep(i,n) for(ll i = 0;i < (ll)n;i++) #define ALL(x) (x).begin(),(x).end() #define sz(c) ((ll)(c).size()) #define LB(A,x) (int)(lower_bound(A.begin(),A.end(),x)-A.begin()) #define UB(A,x) (int)(upper_bound(A.begin(),A.end(),x)-A.begin()) // #define MOD 1000000007 #define MOD 998244353 templateusing min_priority_queue=priority_queue,greater>; templateostream&operator<<(ostream&os,vector&v){for(int i = 0;i < v.size();i++)os<istream&operator>>(istream&is,vector&v){for(T&in:v)is>>in;return is;} templateostream&operator<<(ostream&os,pair&p){os<istream&operator>>(istream&is,pair&p){is>>p.first>>p.second;return is;} template inline bool chmax(T &a,T b){if(a < b){a = b;return true;}return false;} template inline bool chmin(T &a,T b){if(a > b){a = b;return true;}return false;} ld dist(ld x1,ld y1,ld x2, ld y2){return sqrtl((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));} long long extGcd(long long a, long long b, long long &p, long long &q) { if (b == 0) { p = 1; q = 0; return a; } long long d = extGcd(b, a%b, q, p); q -= a/b * p; return d; } // 解が存在する時、リターン値を (x, M) とすると解は x ≡ r_i (mod M) for all i(M = lcm(m_i)) // 解なしの場合は (0, -1) pair crt(const vector &r, const vector &m) { long long x = 0, M = 1; for (int i = 0; i < (int)r.size(); ++i) { long long p, q; long long d = extGcd(M, m[i], p, q); // p is inv of M/d (mod. m[i]/d) if ((r[i] - x) % d != 0) return make_pair(0, -1); long long tmp = (r[i] - x) / d * p % (m[i]/d); x += M * tmp; M *= m[i]/d; } return make_pair((x + M)%M, M); } int main(){ ios_base::sync_with_stdio(0), cin.tie(0); vi r(3),m(3); rep(i,3)cin >> r[i] >> m[i]; rep(i,3)r[i] %= m[i]; auto [x,M] = crt(r,m); if(M == -1)cout << "-1\n"; else cout << x << "\n"; return 0; }