#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define rep(i, n) for (int64_t i = 0; i < (int64_t)(n); i++) #define irep(i, n) for (int64_t i = 0; i <= (int64_t)(n); i++) #define rrep(i, n) for (int64_t i = (n)-1; i >= 0; i--) #define rirep(i, n) for (int64_t i = n; i >= 0; i--) #define chmax(a, b) (a) = max(a, b) #define chmin(a, b) (a) = min(a, b) tuple xgcd(int64_t a, int64_t b) { if (b == 0) { return make_tuple(1, 0, a); } int64_t z, w, d; tie(z, w, d) = xgcd(b, a % b); return make_tuple(w, z - a / b * w, d); } tuple chinese_rem(int64_t a1, int64_t a2, int64_t m1, int64_t m2) { int64_t x, y, d; tie(x, y, d) = xgcd(m1, m2); const int64_t c = a2 - a1; if (c % d != 0) { return make_tuple(0, 0); } const int64_t tmp = c / d * x % (m2 / d); const int64_t sln = a1 + tmp * m1; const int64_t M = m1 / d * m2; return make_tuple((sln % M + M) % M, M); } tuple chinese_rem(const vector& a, const vector& MOD) { if (a.size() != MOD.size()) { stringstream msg; msg << "a.size() is " << a.size() << ", but MOD.size()" << MOD.size() << "\n"; throw msg.str(); } int64_t sln = 0, M = 1; rep(i, a.size()) { tie(sln, M) = chinese_rem(sln, a[i], M, MOD[i]); if (M == 0) { return make_tuple(0, 0); } } return make_tuple(sln, M); } int main() { vector x(3), y(3); rep(i, 3) { cin >> x[i] >> y[i]; } int64_t sln, M; tie(sln, M) = chinese_rem(x, y); cout << (M != 0 ? (sln + M - 1) % M + 1 : -1) << endl; return 0; }