#include<set>
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-8;
const int mod = 1e9 + 7;
const int N = 20;
const int INF = 0x7FFFFFFF;
int T, n, m;
LL A, B, a[N], b[N], ans;
void egcd(LL a, LL b, LL&d, LL&x, LL&y)
{
if (!b) { d = a, x = 1, y = 0; }
else
{
egcd(b, a%b, d, y, x);
y -= x*(a / b);
}
}
LL lmes() {
LL M = a[0], R = b[0], x, y, d;
for (int i = 1; i < m; i++) {
egcd(M, a[i], d, x, y);
if ((b[i] - R) % d) return 0;
x = (b[i] - R) / d*x % (a[i] / d);
R += x*M;
M = M / d*a[i];
R %= M;
}
R = (R + M) % M;
return !R ? n / M : n < R ? 0 : (n - R) / M + 1;
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
rep(i, 0, m - 1) scanf("%lld", &a[i]);
rep(i, 0, m - 1) scanf("%lld", &b[i]);
printf("%d\n", lmes());
}
return 0;
}