#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
// Function to compute the greatest common divisor (GCD)
int gcd(int a, int b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
// Function to compute the least common multiple (LCM)
int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
// Function to find the length of a cycle starting from a node
int find_cycle_length(vector<int>& r, vector<bool>& visited, int start) {
int current = start;
int length = 0;
while (!visited[current]) {
visited[current] = true;
current = r[current];
length++;
}
return length;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> r(n + 1); // r[i] is 1-indexed
for (int i = 1; i <= n; i++) {
cin >> r[i];
}
vector<bool> visited(n + 1, false);
int result = 1;
// Traverse all nodes to find cycles
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
int cycle_length = find_cycle_length(r, visited, i);
result = lcm(result, cycle_length);
}
}
cout << result << endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8bnVtZXJpYz4KI2luY2x1ZGUgPGFsZ29yaXRobT4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovLyBGdW5jdGlvbiB0byBjb21wdXRlIHRoZSBncmVhdGVzdCBjb21tb24gZGl2aXNvciAoR0NEKQppbnQgZ2NkKGludCBhLCBpbnQgYikgewogICAgd2hpbGUgKGIpIHsKICAgICAgICBhICU9IGI7CiAgICAgICAgc3dhcChhLCBiKTsKICAgIH0KICAgIHJldHVybiBhOwp9CgovLyBGdW5jdGlvbiB0byBjb21wdXRlIHRoZSBsZWFzdCBjb21tb24gbXVsdGlwbGUgKExDTSkKaW50IGxjbShpbnQgYSwgaW50IGIpIHsKICAgIHJldHVybiBhIC8gZ2NkKGEsIGIpICogYjsKfQoKLy8gRnVuY3Rpb24gdG8gZmluZCB0aGUgbGVuZ3RoIG9mIGEgY3ljbGUgc3RhcnRpbmcgZnJvbSBhIG5vZGUKaW50IGZpbmRfY3ljbGVfbGVuZ3RoKHZlY3RvcjxpbnQ+JiByLCB2ZWN0b3I8Ym9vbD4mIHZpc2l0ZWQsIGludCBzdGFydCkgewogICAgaW50IGN1cnJlbnQgPSBzdGFydDsKICAgIGludCBsZW5ndGggPSAwOwoKICAgIHdoaWxlICghdmlzaXRlZFtjdXJyZW50XSkgewogICAgICAgIHZpc2l0ZWRbY3VycmVudF0gPSB0cnVlOwogICAgICAgIGN1cnJlbnQgPSByW2N1cnJlbnRdOwogICAgICAgIGxlbmd0aCsrOwogICAgfQoKICAgIHJldHVybiBsZW5ndGg7Cn0KCmludCBtYWluKCkgewogICAgaW50IHQ7CiAgICBjaW4gPj4gdDsKCiAgICB3aGlsZSAodC0tKSB7CiAgICAgICAgaW50IG47CiAgICAgICAgY2luID4+IG47CiAgICAgICAgdmVjdG9yPGludD4gcihuICsgMSk7IC8vIHJbaV0gaXMgMS1pbmRleGVkCiAgICAgICAgZm9yIChpbnQgaSA9IDE7IGkgPD0gbjsgaSsrKSB7CiAgICAgICAgICAgIGNpbiA+PiByW2ldOwogICAgICAgIH0KCiAgICAgICAgdmVjdG9yPGJvb2w+IHZpc2l0ZWQobiArIDEsIGZhbHNlKTsKICAgICAgICBpbnQgcmVzdWx0ID0gMTsKCiAgICAgICAgLy8gVHJhdmVyc2UgYWxsIG5vZGVzIHRvIGZpbmQgY3ljbGVzCiAgICAgICAgZm9yIChpbnQgaSA9IDE7IGkgPD0gbjsgaSsrKSB7CiAgICAgICAgICAgIGlmICghdmlzaXRlZFtpXSkgewogICAgICAgICAgICAgICAgaW50IGN5Y2xlX2xlbmd0aCA9IGZpbmRfY3ljbGVfbGVuZ3RoKHIsIHZpc2l0ZWQsIGkpOwogICAgICAgICAgICAgICAgcmVzdWx0ID0gbGNtKHJlc3VsdCwgY3ljbGVfbGVuZ3RoKTsKICAgICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgY291dCA8PCByZXN1bHQgPDwgZW5kbDsKICAgIH0KCiAgICByZXR1cm4gMDsKfQo=