#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ff first
#define ss second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define trace1(x) cerr<<#x<<": "<<x<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl
template<typename T> T gcd(T a,T b) { if(a==0) return b; return gcd(b%a,a); }
template
<typename T
> T
pow(T a
,T b
, ll m
){T ans
=1; while(b
>0){ if(b
%2==1) ans
=(ans
*a
)%m
; b
/=2; a
=(a
*a
)%m
; } return ans
%m
; }
const int N=1e6+5;
const int MOD=1e9+7;
int a[N], vis[N], fact[N], sieve[N], primef[N];
int modinv(int k)
{
return pow(k
, MOD
-2, MOD
); }
void work(int k)
{
map<int, int> m;
while(k!=1)
{
m[primef[k]]++;
k/=primef[k];
}
for(auto it:m)
{
fact[it.ff]=max(fact[it.ff], it.ss);
}
}
int32_t main()
{
IOS;
int t;
cin>>t;
for(int i=2;i<N;i++)
{
sieve[i]=1;
}
for(int i=2;i<N;i++)
{
if(sieve[i])
{
for(int j=1;i*j<N;j++)
{
sieve[i*j]=0;
primef[i*j]=i;
}
}
}
while(t--)
{
int n;
cin>>n;
memset(fact
, 0, sizeof(fact
)); for(int i=1;i<=n;i++)
{
cin>>a[i];
vis[i]=0;
}
vector<int> cycle;
for(int i=1;i<=n;i++)
{
if(vis[a[i]])
continue;
else
{
int len=0;
int cur=a[i];
while(!vis[cur])
{
vis[cur]=1;
len++;
cur=a[cur];
}
cycle.pb(len);
}
}
for(auto it:cycle)
{
work(it);
}
int ans=1;
for(int i=1;i<N;i++)
{
if(fact[i]==0)
continue;
ans
*=pow(i
, fact
[i
], MOD
); ans%=MOD;
}
cout<<ans<<endl;
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiAKI2RlZmluZSBJT1MgaW9zOjpzeW5jX3dpdGhfc3RkaW8oMCk7IGNpbi50aWUoMCk7IGNvdXQudGllKDApOwojZGVmaW5lIGVuZGwgIlxuIgojZGVmaW5lIGZmIGZpcnN0CiNkZWZpbmUgc3Mgc2Vjb25kCiNkZWZpbmUgbXAgbWFrZV9wYWlyCiNkZWZpbmUgcGIgcHVzaF9iYWNrCiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgaW50IGxvbmcgbG9uZwogCiNkZWZpbmUgdHJhY2UxKHgpICAgICAgICAgICAgICAgIGNlcnI8PCN4PDwiOiAiPDx4PDxlbmRsCiNkZWZpbmUgdHJhY2UyKHgsIHkpICAgICAgICAgICAgIGNlcnI8PCN4PDwiOiAiPDx4PDwiIHwgIjw8I3k8PCI6ICI8PHk8PGVuZGwKI2RlZmluZSB0cmFjZTMoeCwgeSwgeikgICAgICAgICAgY2Vycjw8I3g8PCI6IiA8PHg8PCIgfCAiPDwjeTw8IjogIjw8eTw8IiB8ICI8PCN6PDwiOiAiPDx6PDxlbmRsCiNkZWZpbmUgdHJhY2U0KGEsIGIsIGMsIGQpICAgICAgIGNlcnI8PCNhPDwiOiAiPDxhPDwiIHwgIjw8I2I8PCI6ICI8PGI8PCIgfCAiPDwjYzw8IjogIjw8Yzw8IiB8ICI8PCNkPDwiOiAiPDxk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