#line 1 "test/yukicoder/448.test.cpp" #define PROBLEM "https://yukicoder.me/problems/448" #line 1 "lib/math/crt_mod.hpp" #line 1 "lib/util.hpp" #include #include #include #include namespace tifa_libs { using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; using i128 = __int128_t; using u128 = __uint128_t; } // namespace tifa_libs #line 5 "lib/math/crt_mod.hpp" #line 1 "lib/math/safe_mod.hpp" #line 6 "lib/math/safe_mod.hpp" namespace tifa_libs::math { template , int> = 0> constexpr T safe_mod(T x, std::make_unsigned_t mod) { return ((x %= (T)mod) < 0 ? x + (T)mod : x); } } // namespace tifa_libs::math #line 7 "lib/math/crt_mod.hpp" #include #include #include namespace tifa_libs::math { inline std::optional> crt_mod(const std::vector &a, const std::vector &m, const u32 mod) { assert(a.size() == m.size()); const size_t n = a.size(); std::vector m_cpy(m); for (size_t i = 0; i < n; ++i) { u32 &mi = m_cpy[i]; for (size_t j = 0; j < i; ++j) { u32 &mj = m_cpy[j], d = std::gcd(mi, mj); if (d == 1) continue; if (safe_mod(a[i], d) != safe_mod(a[j], d)) return {}; mi /= d; mj /= d; if (u32 k = std::gcd(mi, d); k != 1) while (d % k == 0) { mi *= k; d /= k; } mj *= d; } } m_cpy.push_back(mod); std::vector pp(n + 1, 1), res(n + 1); for (size_t i = 0; i < n; ++i) { i32 u = (i32)((safe_mod(a[i], m_cpy[i]) - res[i]) * (i64)std::gcd(pp[i], m_cpy[i]) % m_cpy[i]); if (u < 0) u += m_cpy[i]; for (size_t j = i + 1; j <= n; ++j) { res[j] = (i32)((res[j] + (i64)u * pp[j]) % m_cpy[j]); pp[j] = (i32)((i64)(pp[j]) * m_cpy[i] % m_cpy[j]); } } return std::make_pair(res.back(), pp.back()); } } // namespace tifa_libs::math #line 4 "test/yukicoder/448.test.cpp" #include #line 7 "test/yukicoder/448.test.cpp" int main() { tifa_libs::i64 n; std::cin >> n; std::vector r; std::vector m; r.reserve((size_t)n); m.reserve((size_t)n); while (n--) { tifa_libs::i32 x; tifa_libs::u32 y; std::cin >> x >> y; r.push_back(x); m.push_back(y); } auto res = tifa_libs::math::crt_mod(r, m, 1'000'000'007); std::cout << (res ? (tifa_libs::i32)res->first : -1) << '\n'; return 0; }