题目:
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 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.
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
#define N 100005
typedef long long ll;
ll ans,a[N],m[N];
ll gcd(ll a,ll b) {return b == 0 ? a : gcd(b,a % b);}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b){
x = 1;
y = 0;
return a;
}
ans = exgcd(b,a % b,x,y);
int temp = x;
x = y;
y = temp - a / b * y;
return ans;
}
ll inv(ll a,ll b)
{
ll x,y;
exgcd(a,b,x,y);
return ans == 1 ? (x % b + b) % b : -1;
}
ll CRT(ll m[],ll a[],int n)
{
ll x = a[0],M = m[0];
for(int i = 1;i < n;i++){
ll c = a[i] - x;
ll d = gcd(M,m[i]);
if(c % d) return -1;
ll k = (c / d) * inv(M / d,m[i] / d) % (m[i] / d);
x += k * M;
M *= m[i] / d;
}
return (x % M + M) % M;
}
int main()
{
int n;
while(~scanf("%d",&n)){
for(int i = 0;i < n;i++) cin >> m[i] >> a[i];
ll res = CRT(m,a,n);
cout << res << endl;
}
return 0;
}
题意:
有一组同余方程组:
x ≡ a1(mod m1)
x ≡ a2(mod m2)
x ≡ a3(mod m3)
…
x ≡ an(mod mn)
每一组输入都给你n和m1…mn,a1…an。让你求x的值
思路:
这里给你的m1 m2…mn,并不满足两两互质的情况,所以不能用中国剩余定理的一般形式。现在需要推导一下公式。
假设有方程组:x ≡ a1(mod m1) 和 x ≡ a2(mod m2)
x = a1 + k1 * m1
x = a2 + k2 * m2
两式联立得:k1 * m1 - k2 * m2 = a2 - a1
要想满足上面等式,根据扩展欧几里得算法 (a2 - a1)% gcd(m1,m2) == 0
k1 * m1 ≡ (a2 - a1) (mod m2)
设d = gcd(m1,m2) c = a2 - a1
等式两边同除d得:
(m1 / d)* k1 ≡ (c / d)(mod(m2 / d))
k1 = (c / d) * inv(m1 / d)(mod (m2 / d)) //这里inv是逆元的意思
设k = (c / d) * inv(m1 / d)
k1 = k + y * (m2 / d)
将k1带入x = a1 + k1 * m1
得:x = a1 + k * m1 + y * (m1 * (m2 / d))
即:x = a3(mod m3)
其中a3 = a1 + k * m1
m3 = m1 * (m2 / d)
这道题得过程就是根据上述推导来完成的,针对得是m之间不互质得情况下。