#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 100;
const int LOG = 17;
int T;
int n;
int p[N];
int c[N];
int d[N][LOG + 1];
bool odw[N];
int e[N];
vector<int> divi[N];
int g() {
  int best = 101010101;
  for (int i = 1; i <= n; ++i) odw[i] = 0;
  for (int i = 1; i <= n; ++i) {
    if (odw[i]) continue;
    int v = i;
    vector<int> nodes;
    while (!odw[v]) {
      nodes.push_back(v);
      odw[v] = 1;
      v = d[v][0];
    }
    for (auto D : divi[(int)nodes.size()]) {
      if (best <= D) continue;
      for (auto it : nodes) {
        int f = it;
        for (int j = 0; j <= LOG; ++j)
          if ((D >> j) & 1) f = d[f][j];
        e[it] = f;
      }
      for (auto it : nodes) odw[it] = 0;
      for (auto xd : nodes) {
        if (odw[xd]) continue;
        int v = xd;
        bool bad = 0;
        while (!odw[v]) {
          odw[v] = 1;
          if (c[v] != c[e[v]]) {
            bad = 1;
          }
          v = e[v];
        }
        if (!bad) {
          best = min(best, D);
          break;
        }
      }
    }
    for (auto it : nodes) odw[it] = 1;
  }
  return best;
}
void solve() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", p + i);
    d[i][0] = p[i];
  }
  for (int i = 1; i <= n; ++i) scanf("%d", c + i);
  for (int j = 1; j <= LOG; ++j)
    for (int i = 1; i <= n; ++i) d[i][j] = d[d[i][j - 1]][j - 1];
  printf("%d\n", g());
}
int main() {
  for (int i = 1; i <= N - 1; ++i)
    for (int j = i; j < N; j += i) divi[j].push_back(i);
  scanf("%d", &T);
  while (T--) solve();
  return 0;
}
