#include using namespace std; #define REP(i,n) for(int i=0;i<(int)(n);++i) #define REPR(i,n) for (int i=(int)(n)-1;i>=0;--i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() #define valid(y,x,h,w) (0<=y&&y pii; templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (bbasic_ostream& operator<<(basic_ostream&os, const C& c){os<<'[';for(auto i=begin(c);i!=end(c);++i)os<<(i==begin(c)?"":" ")<<*i;return os<<']';} templateostream&operator<<(ostream &o,const pair&t){return o<<'('<void output(ostream&,const Tp&){} templatevoid output(ostream &o,const Tp&t){if(N)o<<',';o<(t);output(o,t);} templateostream&operator<<(ostream&o,const tuple&t){o<<'(';output<0,tuple,Ts...>(o,t);return o<<')';} templatevoid output(T t,char z=10){if(t<0)t=-t,putchar(45);int c[20]; int k=0;while(t)c[k++]=t%10,t/=10;for(k||(c[k++]=0);k;)putchar(c[--k]^48);putchar(z);} templatevoid outputs(T t){output(t);} templatevoid outputs(S a,T...t){output(a,32);outputs(t...);} templatevoid output(T *a,int n){REP(i,n)cout<void output(T *a,int n,int m){REP(i,n)output(a[i],m);} templatebool input(T &t){int n=1,c;for(t=0;!isdigit(c=getchar())&&~c&&c-45;); if(!~c)return 0;for(c-45&&(n=0,t=c^48);isdigit(c=getchar());)t=10*t+c-48;t=n?-t:t;return 1;} templatebool input(S&a,T&...t){input(a);return input(t...);} templatebool inputs(T *a, int n) { REP(i,n) if(!input(a[i])) return 0; return 1;} ll mulmod(ll a, ll n, ll m) { ll res = 0; while(n>=1) { if (n % 2 == 1) res = (res + a) % m; a = a*2%m; n >>= 1; } return res; } ll extgcd(ll a, ll b, ll &x, ll &y) { ll g = a; x = 1; y = 0; if (b) { g = extgcd(b, a%b, y, x); y -= (a/b) * x; } return g; } ll gcd(ll a, ll b) { return b?gcd(b,a%b):a; } ll ChineseRemainderTheorem(const vector &B, const vector &M) { ll all = 1; FOR(it, M) all*=*it; ll res = 0; REP(i,B.size()) { ll x,y; extgcd(M[i], all/M[i], x, y); y = (y+all)%all; res = (res + mulmod(mulmod(B[i],y,all),(all/M[i]),all) + all) % all; } return res; } map factorize(ll n) { // O(√n) map res; for (ll i=2; i*i<=n; ++i) { int cnt = 0; while (n%i==0) { n /= i; cnt++; } if (cnt) { res[i] = cnt; } } if (n!=1) res[n] = 1; return res; } ll lcm(ll a, ll b) { return a/gcd(a,b)*b; } ll lcm(vector v) { ll res = 1; FOR(it, v) res = lcm(res, *it); return res; } int main() { while(1) { vector x(3),y(3); bool eof = 0; REP(i,3) { if (!(cin>>x[i]>>y[i])) eof = 1; } if (eof) break; map > mp; REP(i,3) { map pf = factorize(y[i]); for (auto p : pf) { ll t = 1; REP(i,p.second) t *= p.first; if (mp[p.first].first < t) { mp[p.first] = make_pair(t, x[i] % t); } } } vector B,M; for (auto p : mp) { B.push_back(p.second.second); M.push_back(p.second.first); } ll res = ChineseRemainderTheorem(B,M); if (res == 0) res = lcm(y); bool ok = 1; REP(i,3) { ok &= (res % y[i] == x[i]); } if (ok) cout << res << endl; else cout << -1 << endl; } }