> File Name: 5900.cpp
> Author: jiangyuzhu
> Mail: 834138558@qq.com
> Created Time: 2016/9/22 15:16:35
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 3e2 + 5;
struct node{
int k;
ll v;
}a[maxn];
ll dp[maxn][maxn];
ll sum[maxn];
inline int gcd(int a, int b){return b?gcd(b, a%b):a;}
int main (void)
{
int T;scanf("%d", &T);
while(T--){
int n;scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &a[i].k);
}
memset(sum, 0, sizeof(sum));
for(int i = 0; i < n; i++){
scanf("%lld", &a[i].v);
sum[i] = sum[i - 1] + a[i].v;
}
memset(dp, 0, sizeof(dp));
for(int len = 2; len <= n; len++){
for(int j = 0, k = len - 1; k < n; j++, k++){
if(gcd(a[j].k, a[k].k) > 1 && dp[j + 1][k - 1] == sum[k - 1] - sum[j]){
dp[j][k] = max(dp[j][k], dp[j + 1][k - 1] + a[j].v + a[k].v);
}
for(int i = j; i < k; i++){
dp[j][k] = max(dp[j][k], dp[j][i] + dp[i + 1][k]);
}
}
}
printf("%lld\n", dp[0][n - 1]);
}
return 0;
}