X问题
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4338 Accepted Submission(s): 1389
Problem Description
求在小于等于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)。
Input
输入数据的第一行为一个正整数T,表示有T组测试数据。每组测试数据的第一行为两个正整数N,M (0 < N <= 1000,000,000 , 0 < M <= 10),表示X小于等于N,数组a和b中各有M个元素。接下来两行,每行各有M个正整数,分别为a和b中的元素。
Output
对应每一组输入,在独立一行中输出一个正整数,表示满足条件的X的个数。
Sample Input
3
10 3
1 2 3
0 1 2
100 7
3 4 5 6 7 8 9
1 2 3 4 5 6 7
10000 10
1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
Sample Output
Author
lwg
Source
HDU 2007-1 Programming Contest
/**
中国剩余定理(不互质)
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef __int64 int64;
int64 Mod;
int64 gcd(int64 a, int64 b){
if(b==0)
return a;
return gcd(b,a%b);
}
int64 Extend_Euclid(int64 a, int64 b, int64&x, int64& y){
if(b==0)
{
x=1,y=0;
return a;
}
int64 d = Extend_Euclid(b,a%b,x,y);
int64 t = x;
x = y;
y = t - a/b*y;
return d;
}
//a在模n乘法下的逆元,没有则返回-1
int64 inv(int64 a, int64 n){
int64 x,y;
int64 t = Extend_Euclid(a,n,x,y);
if(t != 1)
return -1;
return (x%n+n)%n;
}
//将两个方程合并为一个
bool merge(int64 a1, int64 n1, int64 a2, int64 n2, int64& a3, int64& n3){
int64 d = gcd(n1,n2);
int64 c = a2-a1;
if(c%d)
return false;
c = (c%n2+n2)%n2;
c /= d;
n1 /= d;
n2 /= d;
c *= inv(n1,n2);
c %= n2;
c *= n1*d;
c += a1;
n3 = n1*n2*d;
a3 = (c%n3+n3)%n3;
return true;
}
//求模线性方程组x=ai(mod ni),ni可以不互质
int64 China_Reminder2(int len, int64* a, int64* n){
int64 a1=a[0],n1=n[0];
int64 a2,n2;
for(int i = 1; i < len; i++)
{
int64 aa,nn;
a2 = a[i],n2=n[i];
if(!merge(a1,n1,a2,n2,aa,nn))
return -1;
a1 = aa;
n1 = nn;
}
Mod = n1;
return (a1%n1+n1)%n1;
}
int64 a[1000],b[1000];
int main(){
int i;
int k;
int n;
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&k);
for(i = 0; i < k; i++)
scanf("%I64d",&a[i]);
for(int i=0;i<k;i++)
scanf("%I64d",&b[i]);
__int64 ans=China_Reminder2(k,b,a);
// cout<<"PPP"<<ans<<endl;
if(ans>n||ans==-1)
printf("0\n");
else
printf("%d\n",(n-ans)/Mod+1-(ans==0?1:0));
}
return 0;
}