#include #include #include using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) typedef long long ll; ll gcd(ll a, ll b) { if(b == 0) { return a; } return gcd(b, a%b); } ll extgcd(ll a, ll b, ll& x, ll& y) { ll d = a; if(b != 0) { d = extgcd(b, a % b, y, x); y -= (a / b) * x; } else { x = 1; y = 0; } return d; } ll mod_inverse(ll a, ll m) { ll x, y; extgcd(a, m, x, y); return (m + x % m) % m; } pair linear_congruence(const vector& B, const vector& M) { ll x = 0, m = 1; rep(i, B.size()) { ll a = m, b = B[i] - x, d = gcd(M[i],a); if(b % d != 0) { return std::make_pair(0,-1); } ll t = b / d * mod_inverse(a / d, M[i] / d) % (M[i] / d); x = x + m * t; m *= M[i] / d; } return std::make_pair(x % m, m); } int main() { vector B(3),M(3); rep(i, 3) { cin >> B[i] >> M[i]; } auto res = linear_congruence(B, M); if(res.second == -1) { cout << -1 << endl; } else { if(res.first == 0) { cout << res.second << endl; } else { cout << res.first << endl; } } return 0; }