#include #include using lint = long long; void solve() { lint r = 0, m = 1; // x % m = r for (int i = 0; i < 3; ++i) { lint nr, nm; std::cin >> nr >> nm; for (int j = 0; j < nm; ++j) { if (r % nm == nr) break; r += m; } if (r % nm != nr) { std::cout << "-1\n"; return; } nm /= std::gcd(m, nm); m *= nm; r %= m; } std::cout << r << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }