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?
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 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.
2 8 7 11 9
31
题目大意:
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
void ex_gcd(ll a,ll b,ll&d,ll&x,ll&y)
{
if(!b)
{
x=1,y=0,d=a;
}
else
{
ex_gcd(b,a%b,d,y,x);
y=y-(a/b)*x;
}
}
int main()
{
ll n,a1,a2,r1,r2;
ll a,b,c,d,x0,y0;
int flag;
while(~scanf("%lld",&n))
{
flag=0;
scanf("%lld%lld",&a1,&r1);
for(int i=1;i<n;i++)
{
scanf("%lld%lld",&a2,&r2);
a=a1,b=a2,c=r2-r1;
ex_gcd(a,b,d,x0,y0);
if(c%d!=0)
flag=1;
int t=b/d;
x0=(x0*(c/d)%t+t)%t;
r1=x0*a1+r1;
a1=a1*(a2/d);
}
if(flag)
printf("-1\n");
else printf("%lld\n",r1);
}
return 0;
}
中国剩余定理非互质版
中国剩余定理求解同余方程要求模数两两互质,在非互质的时候其实也可以计算,这里采用的是合并方程的思想。下面是详细推导。