http://icpc.upc.edu.cn/problem.php?cid=1437&pid=19
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=15;
ll t,a[N],b[N],ans,lcm,f,n,m;
ll gcd(ll a,ll b) {
if (!b) {
return a;
}
return gcd(b, a % b);
}
ll exgcd(ll a,ll b,ll &x,ll&y) {
if (!b) {
x = 1;
y = 0;
return a;
}
ll d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
ll China(ll n) {
ll a1 = a[1], b1 = b[1], a2, b2, x1, y1, x0, g, c;
lcm = a[1];
for (int i = 2; i <= n; i++) {
a2 = a[i];
b2 = b[i];
c = b2 - b1;
g = exgcd(a1, a2, x1, y1);
lcm = lcm * a[i] / gcd(lcm, a[i]);
if (c % g) {
f = 0;
return 0;
}
x0 = x1 * c / g;
ll t = a2 / g;
x0 = (x0 % t + t) % t;
b1 += a1 * x0;
a1 = a2 / g * a1;
}
return b1;
}
int main() {
scanf("%lld", &t);
while (t--) {
scanf("%lld%lld", &n, &m);
for (ll i = 1; i <= m; i++) {
scanf("%lld", &a[i]);
}
for (ll i = 1; i <= m; i++) {
scanf("%lld", &b[i]);
}
f = 1;
ans = China(m);
if (!f || ans > n) {
printf("0\n");
} else {
if (ans <= 0) ans += lcm;
ans = (n - ans) / lcm +1;
printf("%lld\n", ans);
}
}
}