# CodeVS3990：中国余数定理 2 （CRT）

$k\ast \frac{M}{{m}_{1}}\equiv {c}_{1}\left(\phantom{\rule{1em}{0ex}}\mathrm{mod}\phantom{\rule{thinmathspace}{0ex}}\phantom{\rule{thinmathspace}{0ex}}{m}_{1}\right)$

$x\equiv \sum _{i=1}^{k}{c}_{i}\frac{M}{{m}_{i}}Inv\left(\frac{M}{{m}_{i}},{m}_{i}\right)\left(\phantom{\rule{1em}{0ex}}\mathrm{mod}\phantom{\rule{thinmathspace}{0ex}}\phantom{\rule{thinmathspace}{0ex}}M\right)$

CODE：

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn=15;
typedef long long LL;

LL m[maxn];
LL c[maxn];
LL M;

LL X,Y;
LL a,b;
int n;

void Exgcd(LL u,LL v)
{
if (!v) X=1,Y=0;
else
{
Exgcd(v,u%v);
LL p=X;
LL q=Y;
X=q; //!!!
Y=p-u/v*q; //!!!
}
}

int main()
{
freopen("3990.in","r",stdin);
freopen("3990.out","w",stdout);

scanf("%d%I64d%I64d",&n,&a,&b);
M=1;
for (int i=1; i<=n; i++) scanf("%I64d%I64d",&m[i],&c[i]),M*=m[i];
LL k=0;
for (int i=1; i<=n; i++)
{
Exgcd(m[i],M/m[i]%m[i]);
while (Y<0) Y+=m[i];
k=(k+ M/m[i]*c[i]%M*Y%M )%M;
}

a-=k;
b-=k;
LL num=(b+M)/M-(a-1+M)/M; //!!!
if (!num) printf("0\n0\n");
else
{
a=(a+M-1)/M*M+k;
printf("%I64d\n%I64d\n",num,a);
}

return 0;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客