#nt301. 中国剩余定理

中国剩余定理

Chinese Remainder Theorem

Problem Description

There are TT test cases. For each case you are given nn equations and must find xx such that x≡ai(modmi)x \equiv a_i \pmod{m_i} for every ii.

Input Format

The first line contains an integer TT.

For each test case, the first line contains an integer nn, and the following nn lines each contain two integers ai,mia_i, m_i.

Output Format

For each test case, output one integer: the answer. The answer must lie in the range 00 to lcm(m1,m2,…,mn)−1\mathrm{lcm}(m_1, m_2, \dots, m_n) - 1. The data guarantees that a solution exists.

Sample Input

1
3
1 10
2 11
3 12

Sample Output

651

Constraints

T≤1000T \leq 1000, n≤10n \leq 10, 0≤ai<mi≤1090 \leq a_i < m_i \leq 10^9. It is guaranteed that lcm(m1,m2,…,mn)\mathrm{lcm}(m_1, m_2, \dots, m_n) does not exceed 101810^{18}.