【poj2891】Strange Way to Express Integers

2014年5月31日1,4460

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

Sample Output

Hint

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

题解

此题要求求n个同余方程的解,有多组测试数据

ai不互质

用exgcd将俩个同余方程合并成一个

如合并n%a1=b1,n%a2=b2

即a1*x+b1=a2*y+b2

a1*x-a2*y=b2-b1

设a=a1/t,b=a2/t,c=(b2-b1)/t t=gcd(a,b)

若(b2-b1)%t!=0则无解

用exgcd得到a*x+b*y=c的解x0,

通解x=x0+k*b,k为整数

带入a1*x+b1=n

a1*b*k+a1*x0+b1=n

所以b1=b1+a1*x0,a1=a1*b