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 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 9Sample Output
31Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
/**********************一般模线性方程组***********************/ 同样是求这个东西。。 X mod m1=r1 X mod m2=r2 ... ... ... X mod mn=rn 首先,我们看两个式子的情况 X mod m1=r1……………………………………………………………(1) X mod m2=r2……………………………………………………………(2) 则有 X=m1*k1+r1………………………………………………………………(*) X=m2*k2+r2 那么 m1*k1+r1=m2*k2+r2 整理,得 m1*k1-m2*k2=r2-r1 令(a,b,x,y,m)=(m1,m2,k1,k2,r2-r1),原式变成 ax+by=m 熟悉吧? 此时,因为GCD(a,b)=1不一定成立,GCD(a,b) | m 也就不一定成立。所以应该先判 若 GCD(a,b) | m 不成立,则!!!方程无解!!!。 否则,继续往下。 解出(x,y),将k1=x反代回(*),得到X。 于是X就是这两个方程的一个特解,通解就是 X'=X+k*LCM(m1,m2) 这个式子再一变形,得 X' mod LCM(m1,m2)=X 这个方程一出来,说明我们实现了(1)(2)两个方程的合并。 令 M=LCM(m1,m2),R=r2-r1 就可将合并后的方程记为 X mod M = R。 然后,扩展到n个方程。 用合并后的方程再来和其他的方程按这样的方式进行合并,最后就能只剩下一个方程 X mod M=R,其中 M=LCM(m1,m2,...,mn)。 那么,X便是原模线性方程组的一个特解,通解为 X'=X+k*M。 如果,要得到X的最小正整数解,就还是原来那个方法: X%=M; if (X<0) X+=M;
#include<iostream> #include<cstdio> #include<cmath> using namespace std; typedef long long ll; ll m[100005],r[100005]; ll exgcd(ll a,ll b,ll &x,ll &y){ if(b==0){ x=1;y=0; return a; } else { ll r=exgcd(b,a%b,y,x); y-=x*(a/b); return r; } } ll excrt(ll *m,ll *r,int n){ //求最小正整数解 ll M=m[1],R=r[1],x,y,d; for(int i=2;i<=n;i++){ ll d=exgcd(M,m[i],x,y); if((r[i]-R)%d!=0)return -1; x=((r[i]-R)/d*x)%(m[i]/d); R+=M*x; M=M/d*m[i]; //没m[i]*m[i+1]/gcd(m[i],m[i+1]) 求lcm R%=M; } return R>0?R:R+M; } int main() { int i,j,k,t,n; while(scanf("%d",&n)!=EOF){ for(i=1;i<=n;i++){ scanf("%d%d",&m[i],&r[i]); } printf("%lld\n",excrt(m,r,n)); } return 0; }