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, …, akare 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
解题思路:/**********************一般线性同余方程组求解思路***********************/
X mod r1=a1
X mod r2=a2
...
...
...
X mod rn=an
首先,我们看两个式子的情况
X mod a1=r1……………………………………………………………(1)
X mod a2=r2……………………………………………………………(2)
则有
X=a1*y1+r1………………………………………………………………(*)
X=a2*y2+r2
那么 a1*y1+r1=a2*y2+r2
整理,得
a1*y1-a2*y2=r2-r1
令(a,b,x,y,m)=(m1,m2,k1,k2,r2-r1),原式变成
ax+by=m (a=a1,b=a2,m=r2-r1)
熟悉吧?
对于每一个方程GCD(1,ai) | ri=1|ri=0,方程都有解无需验证,只需验证联立后的方程是否有解;
此时,因为GCD(a,b)=1不一定成立,GCD(a,b) | m 也就不一定成立。所以应该先判 若 GCD(a,b) | m 不成立,则!!!方程无解!!!。
否则,继续往下。
解出(x,y),将y1=x反代回(*),得到X。
于是X就是这两个方程的一个特解,通解就是 X'=X+k*LCM(m1,m2) //可以分别从方程(1)(2)的通解形式想到
这个式子再一变形,得 X' mod LCM(m1,m2)=X
这个方程一出来,说明我们实现了(1)(2)两个方程的合并。
令 M=LCM(m1,m2),R=特解X
就可将合并后的方程记为 X mod M = R。
然后,扩展到n个方程。
用合并后的方程再来和其他的方程按这样的方式进行合并,最后就能只剩下一个方程 X mod M=R,其中 M=LCM(m1,m2,...,mn)。
那么,X便是原模线性方程组的一个特解,通解为 X'=X+k*M。
如果,要得到X的最小正整数解,就还是原来那个方法:
min=(x%t+t)%t;
……………………………………详见代码
参考代码+部分注释:
#include
#include
#include
#include