中国剩余定理(构造)
参考博客
中国剩余定理:
设 \(m_1,m_2,\cdots,m_n\) 是两两互质的整数, \(M=\prod_{i=1}^nm_i,M_i=M/m_i,t_i\) 是线性同余方程 \(M_it_i\equiv 1(\bmod m_i)\) 的解,对于任意 \(n\) 个整数 \(a_1,a_2,\cdots,a_n\) 方程组
\[\begin{cases}
x\equiv a_1\ (\bmod p)\\
x\equiv a_2\ (\bmod p)\\
\vdots\\
x\equiv a_n\ (\bmod p)
\end{cases}
\]
的解为 \(x=\sum_{i=1}^na_iM_it_i\)
\(\because M_i=M/m_i\)
\(\therefore M_i\) 是除 \(m_i\) 之外所有模数的倍数
\(\therefore \forall k!=i,a_iM_it_i\equiv0\ (\bmod m_k)\)
\(\because a_iM_it_i\equiv a_i\ (\bmod m_i)\)
\(\therefore x=\sum_{i=1}^na_iM_it_i\) 可使其成立
模板:
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 12;
typedef long long LL;
LL a[maxn], m[maxn];
void exgcd(LL a1, LL b, LL& x, LL& y)
{
if(b){
exgcd(b, a1%b, y, x);
y -= (a1/b)*x;
return ;
}
x = 1;
y = 0;
return ;
}
LL CRT(LL a[], LL m[], int n)
{
LL M=1, ans=0, Mi, x, y;
for(int i=1; i<=n; ++i)
M *= m[i];
for(int i=1; i<=n; ++i)
{
Mi = M/m[i];
exgcd(Mi, m[i], x, y); // 求出 Mi 在 模 mi意义下的乘法逆元
x = (x%m[i] + m[i]) % m[i];
ans = (ans + a[i]*x*Mi) % M;
}
return (ans+M) % M; // 求出最小非负整数解
}
int main()
{
int n;
scanf("%d", &n);
for(int i=1; i<=n; ++i)
scanf("%lld%lld", &m[i], &a[i]); // mi是模数, ai是是在模 mi 意义下的同余数
LL ans = CRT(a, m, n);
printf("%lld\n", ans);
}