#include <cstdio>
#include <cstring>
#include <climits>
#include <algorithm>
const int MAXN = 500;
long long f[MAXN + 1][MAXN + 1], key[MAXN + 1], val[MAXN + 1], ans = 0;
bool canEarnAll[MAXN + 1][MAXN + 1];
int n;
long long gcd(long long a, long long b) {
return !b ? a : gcd(b, a % b);
}
int main() {
int T_T;
scanf("%d", &T_T);
for (int i = 1; i <= T_T; i++) {
memset(f, 0, sizeof(f));
memset(canEarnAll, 0, sizeof(canEarnAll));
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lld", &key[i]);
for (int i = 1; i <= n; i++) scanf("%lld", &val[i]), val[i] += val[i - 1], canEarnAll[i][i - 1] = true;
canEarnAll[n + 1][n] = true;
for (int len = 2; len <= n; len++) {
for (int i = 1; i <= n - len + 1; i++) {
int j = i + len - 1;
canEarnAll[i][j] |= canEarnAll[i + 1][j - 1] & (gcd(key[i], key[j]) != 1);
if (!canEarnAll[i][j]) for (int k = i; k < j; k++) canEarnAll[i][j] |= canEarnAll[i][k] & canEarnAll[k + 1][j];
}
}
for (int len = 2; len <= n; len++) {
for (int i = 1; i <= n - len + 1; i++) {
int j = i + len - 1;
if (canEarnAll[i][j]) f[i][j] = val[j] - val[i - 1];
else for (int k = i; k < j; k++) f[i][j] = std::max(f[i][j], f[i][k] + f[k + 1][j]);
}
}
printf("%lld\n", f[1][n]);
}
return 0;
}