互质情况:
#include <cstdio>//互质 int exGcd(int a,int b,int &x,int &y) { if(b == 0) { x = 1,y = 0; return a; } int d = exGcd(b,a%b,y,x); y -= a/b*x; return d; } int Chinese_Remainder(int mod[],int prime[],int len) { int i,d,x,y,m,n,ret; ret = 0,n = 1; for(i=0; i<len; i++) n *= prime[i]; for(i=0; i<len; i++) { m = n/prime[i]; d = exGcd(prime[i],m,x,y); ret = (ret+y*m*mod[i])%n; } return (n+ret%n)%n; } int main() { int n,i; int mod[15],prime[15]; while(scanf("%d",&n)&&n) { for(i=0; i<n; i++) scanf("%d%d",&prime[i],&mod[i]); printf("%d ",Chinese_Remainder(mod,prime,n)); } return 0; }
不互质的情况
如果flag==0 说明无解
#include <iostream> #include <cstdio> #include <cstring> using namespace std; typedef long long ll; bool flag; ll m[100],a[100],lcm; ll gcd(ll a,ll b){ return b ? gcd(b,a%b) : a; } ll ex_gcd(ll a,ll b,ll &x,ll &y){ if(!b){ x = 1; y = 0; return a; } ll g = ex_gcd(b,a%b,y,x); y -= a / b * x; return g; } ll China(ll n){ ll m1 = m[0],a1 = a[0]; ll m2,a2,k1,k2,x0,g,c; lcm = m[0]; for(int i = 1; i < n; i++){ m2 = m[i]; a2 = a[i]; c = a2 - a1; g = ex_gcd(m1,m2,k1,k2); lcm = lcm * m[i] / gcd(lcm,m[i]); if(c % g){ flag = false; return 0; } x0 = k1 * c / g; ll t = m2 / g; x0 = (x0 % t + t) % t; a1 += m1 * x0; m1 = m2 / g * m1; } return a1; } int main(){ int T; scanf("%d",&T); while(T--){ ll N; int n; scanf("%lld%d",&N,&n); for(int i = 0; i < n; i++) scanf("%lld",&m[i]); for(int i = 0; i < n; i++) scanf("%lld",&a[i]); flag = true; ll ans = China(n); if(!flag || ans > N){ printf("0 "); } else{ if(ans <= 0) ans += lcm; ans = (N - ans) / lcm + 1; printf("%lld ",ans); } } return 0; }