getting wrong answer every time

hi,
can anybody tell me why i am getting wrong answer.i spent a lot of time but all in vain…

#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
int powmod(long long a ,long long b) {
	if(b==0) return 1;
	long long temp=powmod(a,b/2)%mod;
	temp=(temp*temp)%mod;
	if(b%2) {
		temp=((temp%mod)*(a%mod))%mod;
	}
	return temp;
}
int main() {
	long long t,n;
	scanf("%lld",&t);
	while(t--) {
		scanf("%lld",&n);
		long long a[n+1],s,pos[n+1],visited[n+1],len=1,ans=1;
		for(long long i=0;i<=n;i++) {
			visited[i]=0;
		}
		for(long long i=1;i<=n;i++) {
			scanf("%lld",&pos[i]);	
		}
		for(long long i=1;i<=n;i++) {
			if(visited[i]==0) {
				long long product=((ans%mod)*(len%mod))%mod;
				long long gcdInverse=(powmod(__gcd(ans,len),mod-2))%mod;
				ans=(product*gcdInverse)%mod;

				len=1;
				s=pos[i];
				visited[i]=1;
			while(s!=i) {
				len++;
				visited[s]=1;
				s=pos[s];
				}
			}
		
			
		}
		long long product=((ans%mod)*(len%mod))%mod;
				long long gcdInverse=(powmod(__gcd(ans,len),mod-2))%mod;
				ans=(product*gcdInverse)%mod;

		printf("%lld\n",ans);
}
	return 0;
}