Find how many Xs in the positive integers less than or equal to N satisfy: 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). The first line of
Input
data is a positive integer T, indicating that there are T groups of test data. The first line of each set of test data is two positive integers N, M (0 <N <= 1000,000,000, 0 <M <= 10), indicating that X is less than or equal to N, and there are M elements in each of arrays a and b. In the next two lines, each line has M positive integers, which are elements in a and b.
Output
corresponds to each group of inputs, and outputs a positive integer in a separate line, which represents the number of Xs that meet the condition.
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
1
0
3
The breakthrough of this question is that the maximum M is only 10 and each ai only has a range of 1 to 10. Although N is very large, we only need to find the least common multiple lim of all ai, for any x<lim, x%ai=( x+lim)%ai, so the number of qualified numbers in each lim number is the same, and then N is divided into (N/lim) parts, and finally there is no divided number (N%lim). Then proceed separately.
code show as below
#include<bits/stdc++.h>
using namespace std;
const int maxn=3000;
int A[15],B[15],t,n,m;
int num[maxn];
int gcd(int a,int b){
int t=a%b;
while(t!=0){
a=b;b=t;t=a%b;
}
return b;
}
int lcm(int c,int d){
return c*d/gcd(c,d);
}
int main(void){
cin >> t;
while(t--){
for(int i=0;i<=2520;i++)
num[i]=0;
cin >> n >> m;
int lim=1;
for(int i=1;i<=m;i++){
cin >> A[i];
lim=lcm(lim,A[i]);
}
for(int i=1;i<=m;i++){
cin >> B[i];
for(int j=B[i];j<=lim;j+=A[i])
num[j]++;
}
int ans=0;
for(int i=1;i<=lim;i++)
if(num[i]==m)
ans++;
ans*=(n/lim);
lim=n%lim;
for(int i=1;i<=lim;i++)
if(num[i]==m)
ans++;
cout << ans << endl;
}
return 0;
}