#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ull = unsigned long long;
template <class T> using V = vector<T>;
template <class T> using VV = V<V<T>>;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }

#define int ll

#define FOR(i,a,b) for(int i=int(a);i<int(b);i++)
#define REP(i,b) FOR(i,0,b)

ll read(){
	ll x;
	scanf("%lld",&x);
	return x;
}

void print(ll x){
	printf("%lld\n",x);
}

using vi=vector<int>;
#define PB push_back
#define ALL(x) x.begin(),x.end()

int mod;
vi prims;
void InitPrims(){
	int x=mod-1;
	for(int i=2;i*i<=x;i++)if(x%i==0){
		prims.PB(i);
		while(x%i==0)
			x/=i;
	}
	if(x>1)
		prims.PB(x);
}

int pow(int x,int n){
	int res=1;
	while(n){
		if(n&1)res=res*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return res;
}

int GetOrder(int x){
	int res=mod-1;
	for(auto p:prims){
		while(res%p==0){
			if(pow(x,res/p)==1)
				res/=p;
			else
				break;
		}
	}
	return res;
}

int gcd(int a,int b){
	return b?gcd(b,a%b):a;
}

int lcm(int a,int b){
	return a/gcd(a,b)*b;
}

void Solve(){
	int n=read();
	int l=1;
	REP(i,n){
		int g=read();
		int o=GetOrder(g);
		l=lcm(l,o);
	}
	int a=read();
	int ans=0;
	int o=GetOrder(a);
	if(l%o==0)
		ans=1;
	print(ans);
}

signed main() {
	mod=read();
	InitPrims();
	int t=read();
	REP(_,t){
		Solve();
	}
    return 0;
}

