# 【EX_CRT】Strange Way to Express Integers

Description

Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:Choose k different positive integers a1a2…, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1a2, …, ak are properly chosen, m can be determined, then the pairs (airi) can be used to express m.

“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”

Since Elina is new to programming, this problem is too difficult for her. Can you help her?

Input

The input contains multiple test cases. Each test cases consists of some lines.

• Line 1: Contains the integer k.
• Lines 2 ~ k + 1: Each contains a pair of integers airi (1 ≤ i ≤ k).

Output

Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.

Sample Input

```2
8 7
11 9```

Sample Output

`31`

Hint

All integers in the input and the output are non-negative and can be represented by 64-bit integral types.

```#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;

LL gcd(LL a, LL b)
{
if (b == 0)
return a;
return gcd(b, a%b);
}

LL ex_gcd(LL a, LL b, LL&x, LL& y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
LL d = ex_gcd(b, a%b, x, y);
LL t = x;
x = y;
y = t - a / b * y;
return d;
}

LL inv(LL a, LL n)//求a在模n乘法下的逆元，没有则返回-1
{
LL x, y;
LL t = ex_gcd(a, n, x, y);
if (t != 1)
return -1;
return (x%n + n) % n;
}

//将两个方程合并为一个
bool merge(LL a1, LL n1, LL a2, LL n2, LL& a3, LL& n3)
{
LL d = gcd(n1, n2);
LL c = a2 - a1;
if (c%d)
return false;
c = (c%n2 + n2) % n2;
c /= d;
n1 /= d;
n2 /= d;
c *= inv(n1, n2);
c %= n2;
c *= n1 * d;
c += a1;
n3 = n1 * n2*d;
a3 = (c%n3 + n3) % n3;
return true;
}

//求模线性方程组x=ai(mod ni),ni可以不互质
LL ex_China(int len, LL* a, LL* n)
{
LL a1 = a[0], n1 = n[0];
LL a2, n2;
for (int i = 1; i < len; i++)
{
LL aa, nn;
a2 = a[i], n2 = n[i];
if (!merge(a1, n1, a2, n2, aa, nn))
return -1;
a1 = aa;
n1 = nn;
}
return (a1%n1 + n1) % n1;
}
LL a[1000], b[1000];
int main()
{
int i;
int k;
while (cin >> k)
{
for (i = 0; i < k; i++)
cin >> a[i] >> b[i];
cout << ex_China(k, b, a);
}
return 0;
}```