#include using namespace std; #define debug(x) cerr << #x << " = " << (x) << endl #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(),(a).rend() #define mp make_pair #define pb push_back typedef long long ll; typedef long double ld; typedef pair Pii; typedef pair Pll; struct IOSetup { IOSetup() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(16); cerr << fixed << setprecision(16); } } iosetup; template ostream &operator <<(ostream &os, const pair &p) { os << p.first << " " << p.second; return os; } template istream &operator >>(istream &is, pair &p) { is >> p.first >> p.second; return is; } template ostream &operator <<(ostream &os, const vector &v) { for(int i = 0; i < (int) v.size(); i++) os << v[i] << (i+1 == (int) v.size() ? "" : " "); return os; } template istream &operator >>(istream &is, vector &v) { for(int i = 0; i < (int) v.size(); i++) is >> v[i]; return is; } template bool chmax(T &a, const T &b) { if(a < b) { a = b; return true; } return false; } template bool chmin(T &a, const T &b) { if(a > b) { a = b; return true; } return false; } //////////////////////////////////////////////////////// template T extgcd(T a, T b, T &x, T &y) { T d = a; if(b != 0) { d = extgcd(b, a%b, y, x); y -= (a/b)*x; } else { x = 1; y = 0; } return d; } template T CRT(const vector &r, const vector &m) { T r0 = 0, m0 = 1; for(int i = 0; i < (int) r.size(); i++) { T r1 = r[i], m1 = m[i]; if(m0 < m1) { swap(r0, r1); swap(m0, m1); } if(m0 % m1 == 0) { if(r0 % m1 != r1) return 0; continue; } T x, y; T g = extgcd(m0, m1, x, y); T u = m1/g; if((r1-r0) % g != 0) return 0; T lcm = m0*m1/g; T t = (r1-r0)/g*x % u; r0 += m0*t; m0 = lcm; if(r0 < 0) r0 += lcm; } return r0; } int main() { vector r(3), m(3); for(int i = 0; i < 3; i++) cin >> r[i] >> m[i]; cout << (CRT(r, m) == 0 ? -1 : CRT(r, m)) << endl; }