Problems > System of Remainders

System of Remainders

Difficulty: 2200 4000 ms 128 MB

number-theory

Find the smallest non-negative x satisfying x ≡ ri (mod mi) for all i. The moduli are NOT necessarily coprime, so a solution may not exist — print −1 then.

Input: the first line has K; each of the next K lines has ri and mi.

Output: the smallest non-negative solution, or −1.

Constraints:

  • 1 ≤ K ≤ 10
  • 1 ≤ mi ≤ 106
  • 0 ≤ ri < mi

Sample Tests

Input 1
2
2 3
3 5
Output 1
8
Input 2
2
0 4
2 6
Output 2
8

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.