对于x≡ v (mod s) (s0,s2,…sn-1)两两互质
对于n组v和s,求出较小的 满足式子的x的值
#include <iostream>
#include<stdio.h>
using namespace std;
const int MAXN = 100;
int n, v[MAXN], s[MAXN];
//必要的时候用long long
int egcd(int a, int b, int &x, int &y) {
int d;
if (b == 0) {
x = 1; y = 0;
return a;
} else {
d = egcd(b, a%b, y, x);
y -= a/b*x;
return d;
}
}
int lmes()
{
int i, tm=1, mf, y, ret=0, m;
for (i=0; i<n; i++) tm *= s[i];
for (i=0; i<n; i++)
{
m = tm/s[i];
egcd(m, s[i], mf, y);
ret += (v[i]*m*(mf%s[i]))%tm;
}
return (ret+tm)%tm;
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&v[i],&s[i]);
}
printf("%d\n", lmes());
return 0;
}
不互质的情况
///不互质的中国剩余定理
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=100000;
int v[maxn];
int s[maxn];
int ex_gcd(int a,int b,int& x,int& y){
int d;
if(b==0){
x=1;y=0;
return a;
}
d=ex_gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int Chinese( int len)
{
int flag=0;
int n1=v[0],b1=s[0],x,y;
for(int i=1;i<len;i++){
int n2=v[i],b2=s[i];
int bb=b2-b1;
int d=ex_gcd(n1,n2,x,y);
if(bb%d){
flag=1;
break;
}
int k=bb/d*x;
int t=n2/d;
if(t<0)
t=-t;
k=(k%t+t)%t;
b1=b1+n1*k;
n1=n1/d*n2;
}
if(flag)
return -1;
return b1;
}
int main()
{
int t,n,ans=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&v[i]);
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
if(n==1&&s[0]==0)
{
printf("Case %d: %d\n",ans++,v[0]);
continue;
}
printf("Case %d: %d\n",ans++,Chinese(n));
}
return 0;
}