Description

Hard

The Biorhythm Synchronizer

Scientists are studying biological cycles in organisms. Each organism has a cycle with a specific period and a target phase.

Given n organisms, each with a period p[i] and target phase t[i], find the earliest time T (T ≥ 0) when ALL organisms simultaneously reach their target phases.

An organism with period p and target phase t is at its target phase at time T if: T mod p == t

If no such time exists, return -1.

Input Format

The first line contains an integer n, the number of organisms. The next n lines each contain two integers: period and target_phase.

Output Format

Print the earliest time T, or -1 if impossible.

Examples

Example 1

Input
2 3 1 5 2
Output
7
ExplanationAt T=7: 7 mod 3 = 1 ✓, 7 mod 5 = 2 ✓

Example 2

Input
2 4 1 6 3
Output
9
ExplanationAt T=9: 9 mod 4 = 1 ✓, 9 mod 6 = 3 ✓

Constraints

1 ≤ n ≤ 10

1 ≤ period[i] ≤ 1000

0 ≤ target_phase[i] < period[i]

Code

Login
Error

Case 1

Case 2

Input
2 3 1 5 2
Output
No output
Expected
7