#include using namespace std; template T lcm(T a, T b){ return a / __gcd(a, b) * b; } template pair extgcd(T a, T b){ // ax + by = gcd(a, b) if(a == 0){ return pair(0, 1); }else if(b == 0){ return pair(1, 0); } T q = a/b; T r = a%b; auto [s, t] = extgcd(b, r); T y = s - q*t; return pair(t, y); } template pair ctr(const vector& rs, const vector& ms){ assert(rs.size() == ms.size()); int n = rs.size(); T r0 = 0; T m0 = 1; for(int i = 0;i < n; ++i){ T m1 = ms[i]; T r1 = rs[i]; r1 = (r1%m1 + m1)%m1; if(r0 < r1){ swap(r0, r1); swap(m0, m1); } T g = __gcd(m0, m1); if(r0%g != r1%g){ return pair(-1, -1); } auto[x, y] = extgcd(m0, m1); T u1 = (m1 / g); T v = (r1 - r0) / g % u1 * x % u1; r0 += v * m0; m0 *= u1; if (r0 < 0) r0 += m0; } return pair(r0, m0); } void solve(){ vector r(3), m(3); for(int i = 0;i < 3; ++i){ cin >> r[i] >> m[i]; } auto[ar, am] = ctr(r, m); if(ar == 0){ long long l = 1; for(int i = 0;i < 3; ++i){ l = lcm(l, m[i]); } cout << l << endl; return; } cout << ar << endl; } int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); solve(); return 0; }