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.
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.
题目大意:给k个线性同余方程,求这些方程的公共解。
附思路:http://blog.csdn.net/orpinex/article/details/6972654
思路:考虑两个方程的情况
ans = r1(mod a1)
ans = r2(mod a2)①
存在k1使得ans = r1 + k1 * a1
把ans代入①得:r1 + k1 * a1 = r2(mod a2)
k1 * a1 = r2 - r1(mod a2)
存在k2使得k1 * a1 - k2 * a2 = r2 - r1
利用拓展欧几里得求出k1(为了得到最小的非负整数k1,可以让k1 = k1 mod (a2/gcd(a1, a2)))
那么令ans = r1 + k1 * a1
对于多个方程的情况,两个两个地联立解,new_r = ans = r1 + k1 * a1, new_a = lcm(a1, a2)
解析:
关于为了让k1最小要k1 = k1 mod (a2/gcd(a1, a2))。令d = gcd(a1, a2),a1'= a1 / d,a2' = a2 / d ,r' = (r2 - r1) / d,对方程k1 * a1 - k2 * a2 = r2 - r1,两边同时除以d得k1 * a1' - k2 * a2' = r',即k1 * a1' = r' (mod a2'),对于任意解k1 = x',有通解x = x' + a2' = x' + a2 / gcd(a1, a2)。则最小的k1 = (x' + a2 / gcd(a1, a2)) mod (a2 / gcd(a1, a2) = x' mod (a2 / gcd(a1, a2))
关于new_a = lcm(a1, a2)。考虑方程x * a = y * b,两边同时除以gcd(a, b),得到x * a' = y * b',x / y = b' / a',那么有x = kb',y = ka',k∈Z。那么使得方程x * a = y * b成立的x * a = k * b' * a = k * lcm(a, b)。容易想象,p + ax = q + by的每个合理的p + ax的差为lcm(a, b)。即对于方程r1(mod a1) = r2(mod a2)的解也是隔lcm(a1, a2)就出现一个解,即new_a = lcm(a1, a2)。
代码(16MS):
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 typedef long long LL; 7 8 void exgcd(LL a, LL b, LL &d, LL &x, LL &y) { 9 if(!b) d = a, x = 1, y = 0; 10 else { 11 exgcd(b, a % b, d, y, x); 12 y -= x * (a / b); 13 } 14 } 15 16 int main() { 17 LL k, a1, a2, r1, r2; 18 while(scanf("%I64d", &k) != EOF) { 19 bool flag = true; 20 scanf("%I64d%I64d", &a1, &r1); 21 for(int i = 1; i < k; ++i) { 22 scanf("%I64d%I64d", &a2, &r2); 23 if(!flag) continue; 24 LL r = r2 - r1, d, k1, k2; 25 exgcd(a1, a2, d, k1, k2); 26 if(r % d) flag = false; 27 LL t = a2 / d; 28 k1 = (r / d * k1 % t + t) % t; 29 r1 = r1 + a1 * k1; 30 a1 = a1 / d * a2; 31 } 32 printf("%I64d\n", flag ? r1 : -1); 33 } 34 }