#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 998244353;
int n, m, t, a[maxn], b[maxn], vis[maxn], use[maxn], sta[maxn], top;
int in[maxn], sz;
vector<int> g, h[maxn];
void dfs1(int v) {
  sta[++top] = v;
  in[v] = 1;
  vis[v] = 1;
  if (!vis[a[v]])
    dfs1(a[v]);
  else if (in[a[v]]) {
    sz++;
    do {
      h[sz].push_back(sta[top]);
    } while (sta[top--] != a[v]);
  }
  in[v] = 0;
}
void prework() {
  g.clear();
  for (int i = 1; i <= n; i++) vis[i] = 0;
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      top = 0;
      dfs1(i);
    }
  }
  for (int i = 1; i <= sz; i++) {
    g.push_back(h[i].size());
    reverse(h[i].begin(), h[i].end());
  }
}
bool check(int x) {
  for (int i = 1; i <= n; i++) vis[i] = 0;
  for (int i = 1; i <= sz; i++) {
    for (int j = 0; j < h[i].size(); j++) {
      if (vis[h[i][j]]) continue;
      bool f = true;
      for (int k = j; !vis[h[i][k]]; k = (k + x) % h[i].size()) {
        vis[h[i][k]] = 1;
        if (b[h[i][k]] != b[h[i][j]]) {
          f = false;
        }
      }
      if (f) return true;
    }
  }
  return false;
}
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) use[i] = 0;
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
    prework();
    int res = 0x3f3f3f3f;
    for (auto v : g) {
      for (int i = 1; i * i <= v; i++) {
        if (v % i == 0) {
          if (!use[i]) {
            use[i] = 1;
            if (check(i)) res = min(res, i);
          }
          if (!use[v / i]) {
            use[v / i] = 1;
            if (check(v / i)) res = min(res, v / i);
          }
        }
      }
    }
    printf("%d\n", res);
    for (int i = 1; i <= sz; i++) h[i].clear();
    g.clear();
    sz = 0;
  }
  return 0;
}
