【题目链接】:​​click here~~​

【题目大意】:求在小于等于N的正整数中有多少个X满足:X mod a[0] = b[0], X mod a[1] = b[1], X mod a[2] = b[2], …, X mod a[i] = b[i], … (0 < a[i] <= 10)。

【思路】中国剩余定理的应用,注意是求满足一定条件的个数

代码:

/*
* Problem: HDU No.1573
* Running time: 0MS
* Complier: G++
* Author: javaherongwei
* Create Time: 10:39 2015/9/19 星期六
* 中国剩余定理的特殊情况:ai不一定相互互质
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

typedef long long LL;
const int N=15;
LL a[N],b[N];
LL n,m,ans,m1,r1,m2,r2,c,x,t;
bool ok;
int tt;

void ex_gcd(LL a,LL b,LL &d,LL &x,LL &y){/// a*x+b*y=gcd(a,b)=d;(x,y) 为其一组整数解
if(!b){
d=a,x=1,y=0;
}
else{
ex_gcd(b,a%b,d,y,x);
y-=x*(a/b);
}
}

LL ex_crt(LL *a,LL *b,LL n){
LL x,y,d;
m1=a[0],r1=b[0];
for(int i=1; i<m; ++i){
m2=a[i];
r2=b[i];
if(ok) continue;
ex_gcd(m1,m2,d,x,y);
c=r2-r1;
if(c%d){ ///对于方程m1*x+m2*y=c,如果c不是d的倍数就无整数解
ok=1;
continue;
}
t=m2/d; ///对于方程m1x+m2y=c=r2-r1,若(x0,y0)是一组整数解,那么(x0+k*m2/d,y0-k*m1/d)也是一组整数解(k为任意整数)
///其中x0=x*c/d,y0=x*c/d;
x=(c/d*x%t+t)%t;///保证x0是正数,因为x+k*t是解,(x%t+t)%t也必定是正数解(必定存在某个k使得(x%t+t)%t=x+k*t)
r1=m1*x+r1; ///新求的r1就是前i组的解,Mi=m1*x+M(i-1)=r2-m2*y(m1为前i个m的最小公倍数);对m2取余时,余数为r2;
///对以前的m取余时,Mi%m=m1*x%m+M(i-1)%m=M(i-1)%m=r
m1=m1*m2/d;
}
if(ok||n<r1) puts("0");
else{
ans=(n-r1)/m1+1;///m1为ai的最小公倍数,凡是m1*i+r1的都是符合要求的数,其中r1最小
if(r1==0) ans--;
printf("%lld\n",ans);
}
}
int main()
{
scanf("%d",&tt);
while(tt--){
scanf("%lld %lld",&n,&m);
for(int i=0; i<m; ++i) scanf("%lld",&a[i]);
for(int i=0; i<m; ++i) scanf("%lld",&b[i]);
ok=0;
ex_crt(a,b,n);
} return 0;
}