Description
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) 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 ai, ri (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.
给出k组数据,每组数据有2个数,分别是除数和余数,求出满足k组数据的最小整数。
解题思路:
利用扩展欧几里德算法,将每两个同余方程合并为一个同余方程,如此进行下去,直到剩余两个同余方程,求解方程组即可。
代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
__int64 k,m,t;
//扩展欧几里得求最大公约数和解方程ax+by=gcd(a,b)
__int64 exgcd(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
__int64 d=exgcd(b,a%b,x,y);
t=x;
x=y;
y=t-a/b*y;
return d;
}
int main()
{
int i,flag;
__int64 p,q,d,a1,a2,b1,b2,x,c;
while(scanf("%I64d",&k)!=EOF)
{
scanf("%I64d%I64d",&b1,&a1);
flag=0;//标记方程组是否有解,flag=0有解,否则无解
for(i=0;i<k-1;i++)
{
scanf("%I64d%I64d",&b2,&a2);
//flag=1时,方程无解,不在执行下面的操作,只是不停的读数据
if(flag)
continue;
d=exgcd(b1,b2,p,q);//b1,b2的最大公约数
c=a2-a1;
if(c%d)//如果方程Ax+By=c中的c不能整除b1,b2的最大公约数,则方程无解
{
flag=1;
continue;
}
//
t=b2/d;
//最小正整数解
x=(c/d*p%b2+b2)%t;//c/d*p可能为负数,要先模一个b2
a1=x*b1+a1;
b1=b1*b2/d;//b1=lcm(b1,b2)
}
if(flag)
printf("-1\n");
else
printf("%I64d\n",a1);
}
return 0;
}