Problem:
Problem L: Product
Problem
会津君は、素数$P$、自然数からなる集合$G$、自然数$A$を使ってゲームをすることにしました。
まず、会津君は手元の紙に$1$を書きます。その後、以下の一連の操作を任意の回数行います。
$G$から要素を一つ選ぶ。これを$g$とする。
手元の紙に書かれた数と$g$との積を新しく紙に書く。
元々紙に書かれていた数を消す。
手元の紙に書かれた数を$P$で割ったあまりと$A$が等しければ会津君の勝ちで、そうでなければ負けです。$P$、$G$、$A$が与えられたときに会津君が勝つことができるか判定してください。
Input
入力は以下の形式で与えられる。
$P$ $T$
$Test_1$
$\vdots$
$Test_{T}$
入力は複数のテストケースからなる。まず$1$行に素数$P$とテストケースの数$T$が与えられる。$P$は全てのテストケースで共通である。続く$T$行に各テストケースが与えられる。
各テストケースは以下のように与えられる。
$|G|$ $G_1$ $\dots$ $G_{|G|}$ $A$
各テストケースでは、$G$の要素数、$G$の各要素、$A$が順番に空白で区切られて与えられる。
Constraints
入力は以下の条件を満たす。
入力はすべては整数である。
$2 \le P \le 2^{31}-1$
$1 \le T,|G| \le 10^5$
$1 \le G_i,A \le P-1$
$G_i \ne G_j,$ if $i \ne j$
全てのテストケースの$|G|$の総和は$10^5$を超えない。
Output
各テストケースに対して、会津君が勝つことができるならば$1$を、そうでなければ$0$を一行に出力する。
Sample Input 1
7 3
1 1 2
1 2 1
3 1 2 4 5
Sample Output 1
0
1
0
Sample Input 2
1000000007 8
3 2 9 7 5
3 2 9 5 1000001
3 39 1002 65537 12
2 1000000006 518012930 793649232
10 459268180 313723762 835892239 612038995 90424474 366392946 38051435 854115735 5132833 320534710 421820264
1 1 1
1 1 1000000006
1 1000000006 1
Sample Output 2
0
1
1
1
0
1
0
1

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;

#define rep(i,n) for(ll i=0;i<n;++i)
#define all(a) (a).begin(),(a).end()
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
template<class T> T div_floor(T a, T b) { return a / b - ((a ^ b) < 0 && a % b); }
template<class T> T div_ceil(T a, T b) { return a / b + ((a ^ b) > 0 && a % b); }
template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }
template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }

template<typename T>
ostream &operator<<(ostream &os, const vector<T> &a){
    if (a.empty()) return os;
    os << a.front();
    for (auto e : a | views::drop(1)){
        os << ' ' << e;
    }
    return os;
}

void dump(auto ...vs){
    ((cout << vs << ' '), ...) << endl;
}

namespace noya2{

namespace fast_factorize {

/*
    See : https://judge.yosupo.jp/submission/189742
*/

// ---- gcd ----

uint64_t gcd_stein_impl( uint64_t x, uint64_t y ) {
    if( x == y ) { return x; }
    const uint64_t a = y - x;
    const uint64_t b = x - y;
    const int n = __builtin_ctzll( b );
    const uint64_t s = x < y ? a : b;
    const uint64_t t = x < y ? x : y;
    return gcd_stein_impl( s >> n, t );
}

uint64_t gcd_stein( uint64_t x, uint64_t y ) {
    if( x == 0 ) { return y; }
    if( y == 0 ) { return x; }
    const int n = __builtin_ctzll( x );
    const int m = __builtin_ctzll( y );
    return gcd_stein_impl( x >> n, y >> m ) << ( n < m ? n : m );
}

// ---- is_prime ----

uint64_t mod_pow( uint64_t x, uint64_t y, uint64_t mod ) {
    uint64_t ret = 1;
    uint64_t acc = x;
    for( ; y; y >>= 1 ) {
        if( y & 1 ) {
            ret = __uint128_t(ret) * acc % mod;
        }
        acc = __uint128_t(acc) * acc % mod;
    }
    return ret;
}

bool miller_rabin( uint64_t n, const std::initializer_list<uint64_t>& as ) {
    return std::all_of( as.begin(), as.end(), [n]( uint64_t a ) {
        if( n <= a ) { return true; }

        int e = __builtin_ctzll( n - 1 );
        uint64_t z = mod_pow( a, ( n - 1 ) >> e, n );
        if( z == 1 || z == n - 1 ) { return true; }

        while( --e ) {
            z = __uint128_t(z) * z % n;
            if( z == 1 ) { return false; }
            if( z == n - 1 ) { return true; }
        }

        return false;
    });
}

bool is_prime( uint64_t n ) {
    if( n == 2 ) { return true; }
    if( n % 2 == 0 ) { return false; }
    if( n < 4759123141 ) { return miller_rabin( n, { 2, 7, 61 } ); }
    return miller_rabin( n, { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 } );
}

// ---- Montgomery ----

class Montgomery {
    uint64_t mod;
    uint64_t R;
public:
    Montgomery( uint64_t n ) : mod(n), R(n) {
       for( size_t i = 0; i < 5; ++i ) {
          R *= 2 - mod * R;
       }
    }

    uint64_t fma( uint64_t a, uint64_t b, uint64_t c ) const {
        const __uint128_t d = __uint128_t(a) * b;
        const uint64_t    e = c + mod + ( d >> 64 );
        const uint64_t    f = uint64_t(d) * R;
        const uint64_t    g = ( __uint128_t(f) * mod ) >> 64;
        return e - g;
    }

    uint64_t mul( uint64_t a, uint64_t b ) const {
        return fma( a, b, 0 );
    }
};

// ---- Pollard's rho algorithm ----

uint64_t pollard_rho( uint64_t n ) {
    if( n % 2 == 0 ) { return 2; }
    const Montgomery m( n );

    constexpr uint64_t C1 = 1;
    constexpr uint64_t C2 = 2;
    constexpr uint64_t M = 512;

    uint64_t Z1 = 1;
    uint64_t Z2 = 2;
retry:
    uint64_t z1 = Z1;
    uint64_t z2 = Z2;
    for( size_t k = M; ; k *= 2 ) {
        const uint64_t x1 = z1 + n;
        const uint64_t x2 = z2 + n;
        for( size_t j = 0; j < k; j += M ) {
            const uint64_t y1 = z1;
            const uint64_t y2 = z2;

            uint64_t q1 = 1;
            uint64_t q2 = 2;
            z1 = m.fma( z1, z1, C1 );
            z2 = m.fma( z2, z2, C2 );
            for( size_t i = 0; i < M; ++i ) {
                const uint64_t t1 = x1 - z1;
                const uint64_t t2 = x2 - z2;
                z1 = m.fma( z1, z1, C1 );
                z2 = m.fma( z2, z2, C2 );
                q1 = m.mul( q1, t1 );
                q2 = m.mul( q2, t2 );
            }
            q1 = m.mul( q1, x1 - z1 );
            q2 = m.mul( q2, x2 - z2 );

            const uint64_t q3 = m.mul( q1, q2 );
            const uint64_t g3 = gcd_stein( n, q3 );
            if( g3 == 1 ) { continue; }
            if( g3 != n ) { return g3; }

            const uint64_t g1 = gcd_stein( n, q1 );
            const uint64_t g2 = gcd_stein( n, q2 );

            const uint64_t C = g1 != 1 ? C1 : C2;
            const uint64_t x = g1 != 1 ? x1 : x2;
            uint64_t       z = g1 != 1 ? y1 : y2;
            uint64_t       g = g1 != 1 ? g1 : g2;

            if( g == n ) {
                do {
                    z = m.fma( z, z, C );
                    g = gcd_stein( n, x - z );
                } while( g == 1 );
            }
            if( g != n ) {
                return g;
            }

            Z1 += 2;
            Z2 += 2;
            goto retry;
        }
    }
}

void factorize_impl( uint64_t n, std::vector<uint64_t>& ret ) {
    if( n <= 1 ) { return; }
    if( is_prime( n ) ) { ret.push_back( n ); return; }

    const uint64_t p = pollard_rho( n );

    factorize_impl( p, ret );
    factorize_impl( n / p, ret );
}

std::vector<uint64_t> factorize( uint64_t n ) {
    std::vector<uint64_t> ret;
    factorize_impl( n, ret );
    std::sort( ret.begin(), ret.end() );
    return ret;
}

} // namespace fast_factorize

std::vector<std::pair<long long, int>> factorize(long long n){ // 素因数分解
    std::vector<std::pair<long long, int>> ans;
    auto ps = fast_factorize::factorize(n);
    int sz = ps.size();
    for (int l = 0, r = 0; l < sz; l = r){
        while (r < sz && ps[l] == ps[r]) r++;
        ans.emplace_back(ps[l], r-l);
    }
    return ans;
}

std::vector<long long> divisors(long long n){ // 約数列挙
    auto ps = fast_factorize::factorize(n);
    int sz = ps.size();
    std::vector<long long> ans = {1};
    for (int l = 0, r = 0; l < sz; l = r){
        while (r < sz && ps[l] == ps[r]) r++;
        int e = r - l;
        int len = ans.size();
        ans.reserve(len*(e+1));
        long long mul = ps[l];
        while (true){
            for (int i = 0; i < len; i++){
                ans.emplace_back(ans[i]*mul);
            }
            if (--e == 0) break;
            mul *= ps[l];
        }
    }
    return ans;
}

std::vector<long long> divisors(const std::vector<std::pair<long long, int>> &pes){ // 素因数から約数を列挙
    std::vector<long long> ans = {1};
    for (auto [p, e] : pes){
        int len = ans.size();
        ans.reserve(len*(e+1));
        long long mul = p;
        while (true){
            for (int i = 0; i < len; i++){
                ans.emplace_back(ans[i]*mul);
            }
            if (--e == 0) break;
            mul *= p;
        }
    }
    return ans;
}

bool is_prime(long long n){ // 素数判定
    if (n <= 1) return false;
    return fast_factorize::is_prime(n);
}

struct Sieve {
    vector<int> primes, factor, mu;
    Sieve (int N = 1024){
        build(N);
    }
    void request(int N){
        int len = n_max();
        if (len >= N) return ;
        while (len < N) len <<= 1;
        build(len);
    }
    int n_max(){ return factor.size()-1; }
  private:
    void build (int N){
        primes.clear();
        factor.resize(N+1); fill(factor.begin(),factor.end(),0);
        mu.resize(N+1); fill(mu.begin(),mu.end(),1);

        for(int n = 2; n <= N; n++) {
            if (factor[n] == 0){
                primes.push_back(n);
                factor[n] = n;
                mu[n] = -1;
            }
            for (int p : primes){
                if(n * p > N || p > factor[n]) break;
                factor[n * p] = p;
                mu[n * p] = p == factor[n] ? 0 : -mu[n];
            }
        }
    }
} sieve;

int mobius_sieve(int n){ // メビウス関数
    assert(1 <= n);
    if (n>sieve.n_max())sieve.request(n);
    return sieve.mu[n];
}
bool is_prime_sieve(int n){
    if (n <= 2) return n == 2;
    if (n>sieve.n_max())sieve.request(n);
    return sieve.factor[n] == n;
}

vector<pair<int,int>> prime_factorization_sieve(int n){ // 素因数分解
    assert(1 <= n);
    if (n>sieve.n_max())sieve.request(n);
    vector<int> facts;
    while (n > 1){
        int p = sieve.factor[n];
        facts.push_back(p);
        n /= p;
    }
    vector<pair<int,int>> pes;
    int siz = facts.size();
    for (int l = 0, r = 0; l < siz; l = r){
        while (r < siz && facts[r] == facts[l]) r++;
        pes.emplace_back(facts[l],r-l);
    }
    return pes;
}

vector<int> divisor_enumeration_sieve(int n){ // 約数列挙
    auto pes = prime_factorization_sieve(n);
    vector<int> divs = {1};
    for (auto [p, e] : pes){
        vector<int> nxt; nxt.reserve(divs.size() * (e+1));
        for (auto x : divs){
            for (int tt = 0; tt <= e; tt++){
                nxt.push_back(x);
                x *= p;
            }
        }
        swap(divs,nxt);
    }
    return divs;
}

} // namespace noya2
using namespace noya2;


void solve() {
    ll P,T;
    cin>>P>>T;
    vector<pair<ll,int>> PD=factorize(P-1);
    rep(t,T){
        ll N;
        cin>>N;
        ll gg=P-1;
        rep(i,N){
            ll g;
            cin>>g;
            ll R=P-1;
            for (auto [d,e]:PD){
                while (R%d==0){
                    if (modpow(g,R/d,P)==1){
                        R/=d;
                    }
                    else{
                        break;
                    }
                }
            }
            gg=gcd(gg,(P-1)/R);
        }
        ll a;
        cin>>a;
        ll R=P-1;
        for (auto [d,e]:PD){
            while (R%d==0){
                if (modpow(a,R/d,P)==1){
                    R/=d;
                }
                else{
                    break;
                }
            }
        }
        ll ag=(P-1)/R;
        if (ag%gg==0){
            cout<<1<<endl;
        }
        else{
            cout<<0<<endl;
        }
    }
    return;
}


int main() {
    cin.tie(0)->sync_with_stdio(0);
    ll T=1;
    while (T--){
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 280
memory_kb: 3584
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
const ll ILL=2167167167167167167;
const int INF=2100000000;
#define rep(i,a,b) for (int i=(int)(a);i<(int)(b);i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> int LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> int UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,T b){if(b<a){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,T b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
bool yneos(bool a,bool upp=false){if(a){cout<<(upp?"YES\n":"Yes\n");}else{cout<<(upp?"NO\n":"No\n");}return a;}
template<class T> void vec_out(vector<T> &p,int ty=0){
    if(ty==2){cout<<'{';for(int i=0;i<(int)p.size();i++){if(i){cout<<",";}cout<<'"'<<p[i]<<'"';}cout<<"}\n";}
    else{if(ty==1){cout<<p.size()<<"\n";}for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}}
template<class T> T vec_min(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmin(ans,x);return ans;}
template<class T> T vec_max(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmax(ans,x);return ans;}
template<class T> T vec_sum(vector<T> &a){T ans=T(0);for(auto &x:a) ans+=x;return ans;}
int pop_count(long long a){int res=0;while(a){res+=(a&1),a>>=1;}return res;}
template<class T> T square(T a){return a * a;}

#include <atcoder/modint>
using mint = atcoder::modint;

// return val=p(N)
// a=p[0].first^p[0].second * ... *p[N-1].first^p[N-1].second
// for all i: p[i].first is prime number
// O(sqrt(val))
std::vector<std::pair<long long,long long>> Prime_factorization(long long val){
    assert(val>=1);
    if(val==1){
        return {};
    }
    int ind=0;
    std::vector<std::pair<long long,long long>> ans;
    for(long long i=2;i*i<=val;i++){
        if(val%i!=0) continue;
        ans.push_back({i,0});
        while(val%i==0){
            ans[ind].second++;
            val/=i;
        }
        ind++;
    }
    if(val!=1) ans.push_back({val,1});
    return ans;
}

void solve();
// POP'N ROLL MUSIC / TOMOO
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    // cin >> t;
    rep(i, 0, t) solve();
}

void solve(){
    int P, T;
    cin >> P >> T;
    mint::set_mod(P);
    auto D = Prime_factorization(P - 1);
    auto f = [&](int a) -> int {
        int ans = P - 1;
        for (auto [p, e] : D){
            int tmp = P - 1;
            rep(rp, 0, e){
                tmp /= p;
                if ((mint(a)).pow(tmp) != 1){
                    ans /= p;
                }
            }
        }
        // cout << a << " " << ans << "\n";
        return ans;
    };
    while (T--){
        int N;
        cin >> N;
        int A = P - 1;
        rep(rp, 0, N){
            int a;
            cin >> a;
            A = gcd(A, f(a));
        }
        int B;
        cin >> B;
        B = f(B);
        cout << (B % A == 0 ? 1 : 0) << "\n";
    }
}
accuracy: 1
time_ms: 310
memory_kb: 3584
final_rank: 3

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <array>
#include <tuple>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <bitset>
#include <cmath>
#include <functional>
#include <cassert>
#include <climits>
#include <iomanip>
#include <numeric>
#include <memory>
#include <random>
#include <thread>
#include <chrono>
#define allof(obj) (obj).begin(), (obj).end()
#define range(i, l, r) for(int i=l;i<r;i++)
#define unique_elem(obj) obj.erase(std::unique(allof(obj)), obj.end())
#define bit_subset(i, S) for(int i=S, zero_cnt=0;(zero_cnt+=i==S)<2;i=(i-1)&S)
#define bit_kpop(i, n, k) for(int i=(1<<k)-1,x_bit,y_bit;i<(1<<n);x_bit=(i&-i),y_bit=i+x_bit,i=(!i?(1<<n):((i&~y_bit)/x_bit>>1)|y_bit))
#define bit_kth(i, k) ((i >> k)&1)
#define bit_highest(i) (i?63-__builtin_clzll(i):-1)
#define bit_lowest(i) (i?__builtin_ctzll(i):-1)
#define sleepms(t) std::this_thread::sleep_for(std::chrono::milliseconds(t))
using ll = long long;
using ld = long double;
using ul = uint64_t;
using pi = std::pair<int, int>;
using pl = std::pair<ll, ll>;
using namespace std;

template<typename F, typename S>
std::ostream &operator<<(std::ostream &dest, const std::pair<F, S> &p){
  dest << p.first << ' ' << p.second;
  return dest;
}
template<typename T>
std::ostream &operator<<(std::ostream &dest, const std::vector<T> &v){
  int sz = v.size();
  if(sz==0) return dest;
  for(int i=0;i<sz-1;i++) dest << v[i] << ' ';
  dest << v[sz-1];
  return dest;
}
template<typename T>
vector<T> read_vec(size_t sz){
  std::vector<T> v(sz);
  for(int i=0;i<(int)sz;i++) std::cin >> v[i];
  return v;
}
template<typename T, typename... Tail>
auto read_vec(size_t sz, Tail ...tail){
  auto v = std::vector<decltype(read_vec<T>(tail...))>(sz);
  for(int i=0;i<(int)sz;i++) v[i] = read_vec<T>(tail...);
  return v;
}
void io_init(){
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}
template<typename Val>
struct accumulate1d{
  std::vector<Val> sum;
  accumulate1d(){}
  accumulate1d(const std::vector<Val> &v): sum(v){
    for(int i = 1; i < v.size(); i++) sum[i] = sum[i - 1] + v[i];
  }
  // [0, r)の和, 範囲外の部分は全て単位元
  Val query(int r){
    r = std::min(r, (int)sum.size());
    if(r <= 0) return 0;
    return sum[r - 1];
  }
  // [l, r)の和, 範囲外の部分は全て単位元
  Val query(int l, int r){
    l = std::max(l, 0);
    r = std::min(r, (int)sum.size());
    if(r <= l) return 0;
    return (l == 0 ? sum[r - 1] : (sum[r - 1] - sum[l - 1]));
  }
  void push_back(Val x){
    Val y = (sum.empty() ? 0 : sum.back());
    sum.push_back(y + x);
  }
  void pop_back(){
    assert(!sum.empty());
    sum.pop_back();
  }
  // [0, k]がx以上になる最小インデックス, ない場合はn
  int lower_bound(Val x){
    return std::lower_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
  // [0, k]がxより大きくなる最小インデックス, ない場合はn
  int upper_bound(Val x){
    return std::upper_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
};



#include <type_traits>
#include <ostream>


// @param m `1 <= m`
constexpr long long safe_mod(long long x, long long m){
  x %= m;
  if (x < 0) x += m;
  return x;
}
struct barrett{
  unsigned int _m;
  unsigned long long im;
  explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1){}
  unsigned int umod()const{return _m;}
  unsigned int mul(unsigned int a, unsigned int b)const{
    unsigned long long z = a;
    z *= b;
#ifdef _MSC_VER
    unsigned long long x;
    _umul128(z, im, &x);
#else
    unsigned long long x = (unsigned long long)(((unsigned __int128)(z) * im) >> 64);
#endif
    unsigned long long y = x * _m;
    return (unsigned int)(z - y + (z < y ? _m : 0));
  }
};
// @param n `0 <= n`
// @param m `1 <= m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m){
  if(m == 1) return 0;
  unsigned int _m = (unsigned int)(m);
  unsigned long long r = 1;
  unsigned long long y = safe_mod(x, m);
  while(n){
    if (n & 1) r = (r * y) % _m;
    y = (y * y) % _m;
    n >>= 1;
  }
  return r;
}
constexpr bool is_prime_constexpr(int n) {
  if (n <= 1) return false;
  if (n == 2 || n == 7 || n == 61) return true;
  if (n % 2 == 0) return false;
  long long d = n - 1;
  while (d % 2 == 0) d /= 2;
  constexpr long long bases[3] = {2, 7, 61};
  for(long long a : bases){
    long long t = d;
    long long y = pow_mod_constexpr(a, t, n);
    while(t != n - 1 && y != 1 && y != n - 1){
      y = y * y % n;
      t <<= 1;
    }
    if(y != n - 1 && t % 2 == 0){
      return false;
    }
  }
  return true;
}
template<int n>
constexpr bool is_prime = is_prime_constexpr(n);

constexpr int primitive_root_constexpr(int m){
  if(m == 2) return 1;
  if(m == 167772161) return 3;
  if(m == 469762049) return 3;
  if(m == 754974721) return 11;
  if(m == 998244353) return 3;
  int divs[20] = {};
  divs[0] = 2;
  int cnt = 1;
  int x = (m - 1) / 2;
  while (x % 2 == 0) x /= 2;
  for(int i = 3; (long long)(i)*i <= x; i += 2){
    if(x % i == 0){
      divs[cnt++] = i;
      while(x % i == 0){
        x /= i;
      }
    }
  }
  if(x > 1) divs[cnt++] = x;
  for(int g = 2;; g++){
    bool ok = true;
    for(int i = 0; i < cnt; i++){
      if(pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1){
        ok = false;
        break;
      }
    }
    if(ok)return g;
  }
}
template <int m>
constexpr int primitive_root = primitive_root_constexpr(m);

int ceil_pow2(int n){
  int x = 0;
  while ((1U << x) < (unsigned int)(n)) x++;
  return x;
}
int bsf(unsigned int n){
  return __builtin_ctz(n);
}
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b){
  a = safe_mod(a, b);
  if(a == 0) return {b, 0};
  long long s = b, t = a;
  long long m0 = 0, m1 = 1;
  while (t){
    long long u = s / t;
    s -= t * u;
    m0 -= m1 * u;
    auto tmp = s;
    s = t;
    t = tmp;
    tmp = m0;
    m0 = m1;
    m1 = tmp;
  }
  if(m0 < 0) m0 += b / s;
  return {s, m0};
}



template<int m>
long long modpow(long long a, long long b){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}
// @param 0 <= b, 0 < m
long long modpow(long long a, long long b, int m){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}

struct modint_base {};

template<int id> 
struct dynamic_modint : modint_base{
  using mint = dynamic_modint;
public:
  static int mod(){return (int)(bt.umod());}
  static void set_mod(int m){
    assert(1 <= m);
    bt = barrett(m);
  }
  static mint raw(int v){
    mint x;
    x._v = v;
    return x;
  }
  dynamic_modint(): _v(0){}
  template <class T>
  dynamic_modint(T v){
    long long x = v % (long long)(mod());
    if (x < 0) x += mod();
    _v = x;
  }
  unsigned int val()const{return _v;}
  mint& operator++(){
    _v++;
    if(_v == umod()) _v = 0;
    return *this;
  }
  mint& operator--(){
    if (_v == 0) _v = umod();
    _v--;
    return *this;
  }
  mint operator++(int){
    mint result = *this;
    ++*this;
    return result;
  }
  mint operator--(int){
    mint result = *this;
    --*this;
    return result;
  }
  mint& operator+=(const mint& rhs){
    _v += rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator-=(const mint& rhs){
    _v += mod() - rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator*=(const mint& rhs){
    _v = bt.mul(_v, rhs._v);
    return *this;
  }
  mint& operator/=(const mint& rhs){return *this = *this * rhs.inv();}
  mint operator+()const{return *this;}
  mint operator-()const{return mint() - *this;}
  mint pow(long long n)const{
    assert(0 <= n);
    mint x = *this, r = 1;
    while(n){
      if (n & 1) r *= x;
      x *= x;
      n >>= 1;
    }
    return r;
  }
  mint inv()const{
    auto eg = inv_gcd(_v, mod());
    assert(eg.first == 1);
    return eg.second;
  }
  friend mint operator+(const mint& lhs, const mint& rhs){return mint(lhs) += rhs;}
  friend mint operator-(const mint& lhs, const mint& rhs){return mint(lhs) -= rhs;}
  friend mint operator*(const mint& lhs, const mint& rhs){return mint(lhs) *= rhs;}
  friend mint operator/(const mint& lhs, const mint& rhs){return mint(lhs) /= rhs;}
  friend bool operator==(const mint& lhs, const mint& rhs){return lhs._v == rhs._v;}
  friend bool operator!=(const mint& lhs, const mint& rhs){return lhs._v != rhs._v;}
private:
  unsigned int _v;
  static barrett bt;
  static unsigned int umod(){return bt.umod();}
};
template <int id>
barrett dynamic_modint<id>::bt(998244353);
using modint = dynamic_modint<-1>;
template<int id>
std::ostream &operator<<(std::ostream &dest, const dynamic_modint<id> &a){
  dest << a.val();
  return dest;
}
#include <limits>
// 符号なし整数 -> 符号付き整数
template <class T>
using make_signed_t = typename std::make_signed<T>::type;
// 符号付き整数 -> 符号なし整数
template <class T>
using make_unsigned_t = typename std::make_unsigned<T>::type;
// 符号付き32bit整数か
template <class T>
using is_signed_int32 = typename std::conditional<std::is_same<T, int>::value || std::is_same<T, int32_t>::value, std::true_type, std::false_type>::type;
// 符号なし32bit整数か
template <class T>
using is_unsigned_int32 = typename std::conditional<std::is_same<T, unsigned int>::value || std::is_same<T, uint32_t>::value, std::true_type, std::false_type>::type;
// 符号付き64bit整数か
template <class T>
using is_signed_int64 = typename std::conditional<std::is_same<T, long long int>::value || std::is_same<T, int64_t>::value, std::true_type, std::false_type>::type;
// 符号なし64bit整数か
template <class T>
using is_unsigned_int64 = typename std::conditional<std::is_same<T, unsigned long long>::value || std::is_same<T, uint64_t>::value, std::true_type, std::false_type>::type;
// 符号付き128bit整数か
template <class T>
using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type;
// 符号なし128bit整数か
template <class T>
using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 128bit整数か
template <class T>
using is_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value || std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの整数か
template<class T>
using is_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value || is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号付き整数か
template<class T>
using is_signed_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号なし整数か
template<class T>
using is_unsigned_intle64 = typename std::conditional<is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;

template<class T>
using is_not_t = typename std::conditional<T::value, std::false_type, std::true_type>::type;

unsigned long long random_once(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  static unsigned long long ret = engine();
  return ret;
}

unsigned long long random_number(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  return engine();
}

// [low, high]
unsigned long long random_number(unsigned long long low, unsigned long long high){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  assert(high >= low);
  unsigned long long diff = high - low + 1;
  return engine() % diff + low;
}
unsigned long long ceillog2(unsigned long long x){
  int res = 1;
  while((1ULL << res) < x) res++;
  return res;
}

// uint32 : uKey ∈ [0, 2^31 - 1)
// uint64 : uKey ∈ [0, 2^63 - 1)
template<typename uKey, typename Val>
struct uhash_map{
  static_assert(is_unsigned_intle64<uKey>::value, "uKey must be unsigned integer (32 or 64bit)");
private:
  using Key = typename std::make_signed<uKey>::type;
  static constexpr int initial_size = 8; // 指定しなかった場合の初期サイズ
  static constexpr float alpha = 0.7; // 占有率がこれを超えると再構築
  static constexpr Key null_val = std::numeric_limits<Key>::min();
  static constexpr Key inf = std::numeric_limits<Key>::max();
  static const unsigned long long r;
  int table_size, table_size_mod;
  int occupied_cnt, elem_cnt; // 使われている要素の数, そのうちまだ消されていない要素の数
  std::vector<std::pair<Key, Val>> v;
  size_t hash(unsigned long long x){
    x += r;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return (x ^ (x >> 31)) & table_size_mod;
  }
  void expand(){
    std::vector<std::pair<Key, Val>> tmp(elem_cnt, {null_val, Val()});
    for(int i = 0, j = 0; i < table_size; i++) if(v[i].first >= 0) tmp[j++] = v[i];
    occupied_cnt = elem_cnt = 0;
    table_size <<= 1;
    table_size_mod = table_size - 1;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
    for(int i = 0; i < tmp.size(); i++) emplace_inner(tmp[i].first, tmp[i].second);
  }
  void emplace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        if(v[i].first == -x - 1){
          elem_cnt++;
          v[i] = {x, y};
        }
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void emplace_replace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt += (v[i].first == -x - 1);
        v[i] = {x, y};
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void erase_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return;
      else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt -= (v[i].first == x);
        v[i].first = -x - 1;
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  bool find_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return false;
      else if(v[i].first == x || v[i].first == -x - 1) return v[i].first == x;
      i = (i + 1) & table_size_mod;
    }
  }
  std::pair<bool, Val> at_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return std::make_pair(false, v[i].second);
      else if(v[i].first == x || v[i].first == -x - 1) return (v[i].first == x ? std::make_pair(true, v[i].second) : std::make_pair(false, v[i].second));
      i = (i + 1) & table_size_mod;
    }
  }
public:
  uhash_map(): table_size(initial_size), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  uhash_map(int _sz): table_size(1 << ceillog2(_sz)), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  // 追加, すでにある場合は無視
  void emplace(uKey x, Val y){
    assert(x < inf);
    emplace_inner(x, y);
  }
  // 追加, すでにある場合は置き換える
  void emplace_replace(uKey x, Val y){
    assert(x < inf);
    emplace_replace_inner(x, y);
  }
  // 削除, 無い場合は無視
  void erase(uKey x){
    assert(x < inf);
    erase_inner(x);
  }
  // 検索
  bool find(uKey x){
    assert(x < inf);
    return find_inner(x);
  }
  // 存在するか, 存在する場合その値
  std::pair<bool, Val> at(uKey x){
    assert(x < inf);
    return at_inner(x);
  }
  int size(){
    return elem_cnt;
  }
  bool empty(){
    return elem_cnt == 0;
  }
  std::vector<std::pair<uKey, Val>> enumerate(){
    std::vector<std::pair<uKey, Val>> res;
    for(int i = 0; i < table_size; i++) if(v[i].first >= 0) res.push_back(v[i]);
    return res;
  }
  void clear(){
    table_size = initial_size;
    table_size_mod = table_size - 1;
    occupied_cnt = elem_cnt = 0;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
  }
};
template<typename uKey, typename Val>
const unsigned long long uhash_map<uKey, Val>::r = random_number();
// 素数m, 数列A, bを与える
// 各a_iに対してb ^ k ≡ a_iを満たすkを返す
template<typename mint>
std::vector<int> bsgs_many(int b, const std::vector<int> &A){
  int init_size = 2e6; // mod998244353, |A| = 2e5で設定 メモリ130MB |A|が大きい場合は1e7などにする 
  init_size = std::min(init_size, mint::mod());
  // 前処理 O(init_size)
  uhash_map<unsigned, int> mp(init_size * 2);
  mint x = 1;
  for(int i = 0; i < init_size; i++){
    mp.emplace(x.val(), i);
    x *= b;
  }
  std::vector<int> res;
  int imax = ((long long)mint::mod() + init_size - 1) / init_size;
  mint y = mint(b).pow((long long)2 * mint::mod() - 2 - init_size); // b ^ {-init_size}
  // 計算 O(|A| * mod / init_size)
  for(int a : A){
    x = a;
    for(int i = 0; i < imax; i++){
      auto [f, j] = mp.at(x.val());
      if(f){
        res.push_back(i * init_size + j);
        break;
      }
      x *= y;
    }
  }
  return res;
}
#include <cstdint>

struct barrett_reduction{
  unsigned int mod;
  unsigned long long m;
  barrett_reduction(unsigned int _mod) : mod(_mod){
    m = ((__uint128_t)1 << 64) / mod;
  }
  unsigned int reduce(unsigned int a){
    unsigned long long q = ((__uint128_t)a * m) >> 64;
    a -= q * mod; // 0 <= a < 2 * mod
    // return a;
    return a >= mod ? a - mod : a;
  }
  unsigned int mul(unsigned int a, unsigned int b){
    return reduce((unsigned long long)a * b);
  }
  // {gcd(a, mod), x}, such that a * x ≡ gcd(a, mod)
  std::pair<unsigned int, unsigned int> inv(unsigned int a){
    if(a >= mod) a = reduce(a);
    if(a == 0) return {mod, 0};
    unsigned int s = mod, t = a;
    long long m0 = 0, m1 = 1;
    while(t){
      int u = s / t;
      s -= t * u;
      m0 -= m1 * u;
      std::swap(m0, m1);
      std::swap(s, t);
    }
    if(m0 < 0) m0 += mod / s;
    return {s, m0};
  }
};
// 64bit mod対応
// R = 2^64
// 偶数modだと壊れる
struct montgomery_reduction_64bit{
private:
  // [0, 2 * MOD)
  inline uint64_t reduce_unsafe(__uint128_t x) const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x;
  }
  void _set_mod(uint64_t mod){
    assert((mod < (1ULL << 63)) && (mod & 1));
    MOD = mod;
    NEG_INV = 0;
    __uint128_t s = 1, t = 0;
    for(int i = 0; i < 64; i++){
      if (~t & 1) {
        t += MOD;
        NEG_INV += s;
      }
      t >>= 1;
      s <<= 1;
    }
    R2 = ((__uint128_t)1 << 64) % MOD;
    R2 = R2 * R2 % MOD;
    ONE = generate(1);
  }
  __uint128_t MOD, NEG_INV, R2;
  uint64_t ONE;
public:
  montgomery_reduction_64bit(){}
  montgomery_reduction_64bit(uint64_t mod){_set_mod(mod);}
  void set_mod(uint64_t mod){
    _set_mod(mod);
  }
  uint64_t mod()const{
    return MOD;
  }
  inline uint64_t one()const{
    return ONE;
  }
  inline uint64_t generate(uint64_t x)const{
    return reduce((__uint128_t)x * R2);
  }
  inline uint64_t reduce(__uint128_t x)const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x < MOD ? x : x - MOD;
  }
  inline uint64_t fix(uint64_t x)const{
    return x < MOD ? x : x - MOD;
  }
  // [0, 2MOD)
  inline uint64_t mul(uint64_t mx, uint64_t my)const{
    return reduce_unsafe((__uint128_t)mx * my);
  }
  inline uint64_t mul_safe(uint64_t mx, uint64_t my)const{
    return reduce((__uint128_t)mx * my);
  }
  // [0, 2MOD)
  inline uint64_t add(uint64_t mx, uint64_t my)const{
    return (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
  }
  inline uint64_t add_safe(uint64_t mx, uint64_t my)const{
    uint64_t res = (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
    return res >= MOD ? res - MOD : res;
  }
  // [0, 2MOD)
  inline uint64_t sub(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    return mx >= my ? mx - my : mx + MOD - my;
  }
  inline uint64_t sub_safe(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    uint64_t res = mx >= my ? mx - my : mx + MOD - my;
    return res >= MOD ? res - MOD : res;
  }
  inline uint64_t pow(uint64_t ma, uint64_t b)const{
    uint64_t ret = one();
    while(b){
      if(b & 1) ret = mul(ret, ma);
      ma = mul(ma, ma);
      b >>= 1;
    }
    return ret;
  }
  inline uint64_t pow_safe(uint64_t ma, uint64_t b)const{
    return fix(pow(ma, b));
  }
};
unsigned long long mod_pow_mr(unsigned long long a, unsigned long long b, unsigned long long m){
  montgomery_reduction_64bit mr(m);
  return mr.reduce(mr.pow(mr.generate(a), b));
}
bool _miller_rabin_mr(unsigned long long n, const montgomery_reduction_64bit &mr){
  static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
  static std::vector<unsigned long long> A{2, 325, 9375, 28178, 450775, 9780504, 1795265022};
  static std::vector<unsigned long long> B{2, 7, 61};
  if(n <= 1) return false;
  if(n <= 50){
    for(int l = n < 20 ? 0 : 8, r = n < 20 ? 8 : 15; l < r; l++) if(small_p[l] == n) return true;
    return false;
  }
  if(!(n & 1)) return false;
  unsigned long long d = n - 1;
  unsigned long long one = mr.one(), mone = mr.generate(n - 1);
  d >>= __builtin_ctzll(d);
  for(unsigned long long a : (n >> 32) ? A : B){
    if(a % n == 0) continue;
    unsigned long long d2s = d; // d * 2^s, 0 <= s <= (n - 1)が2で割れる回数
    unsigned long long y = mr.pow_safe(mr.generate(a), d);
    while(d2s != n - 1 && y != one && y != mone){
      y = mr.mul_safe(y, y);
      d2s <<= 1;
    }
    if(y != mone && !(d2s & 1)) return false;
  }
  return true;
}
bool miller_rabin_mr(unsigned long long n){
  if(n % 2 == 0) return n == 2 ? true : false;
  montgomery_reduction_64bit mr(n);
  return _miller_rabin_mr(n, mr);
}
// https://en.wikipedia.org/wiki/Binary_GCD_algorithm
unsigned long long binary_gcd(unsigned long long a, unsigned long long b){
  if(!a || !b) return !a ? b : a;
  int shift = __builtin_ctzll(a | b); // [1] gcd(2a', 2b') = 2 * gcd(a', b')
  a >>= __builtin_ctzll(a);
  do{
    // if b is odd
    // gcd(2a', b) = gcd(a', b), if a = 2a'(a is even)
    // gcd(a, b) = gcd(|a - b|, min(a, b)), if a is odd
    b >>= __builtin_ctzll(b); // make b odd
    if(a > b) std::swap(a, b);
    b -= a;
  }while(b); // gcd(a, 0) = a
  return a << shift; // [1]
}
unsigned long long generate_random_prime(unsigned long long min_n = 2, unsigned long long max_n = ~0ULL){
  std::random_device seed_gen;
  std::mt19937_64 engine(seed_gen());
  __uint128_t len = max_n - min_n + 1;
  // https://en.wikipedia.org/wiki/Prime_number_theorem
  while(true){
    unsigned long long a = engine() % len + min_n;
    if(miller_rabin_mr(a)){
      return a;
    }
  }
}
namespace rho_factorization{
  unsigned long long rho(unsigned long long n){
    static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};

    for(int sp : small_p) if(n % sp == 0) return sp; // n < 50

    montgomery_reduction_64bit mr(n);
    if(_miller_rabin_mr(n, mr)) return n;

    auto try_factorize = [n, mr](unsigned long long c){
      c = mr.generate(c);
      auto f = [mr, c](unsigned long long mx){
        return mr.add(mr.mul(mx, mx), c);
      };
      unsigned long long m = 1LL << ((64 - __builtin_clzll(n)) / 8);
      unsigned long long y = n, r = 1, q = 1;
      unsigned long long x, g, k, ys;
      do{
        x = y;
        y = mr.generate(y);
        for(int i = 0; i < r; i++) y = f(y);
        y = mr.reduce(y);

        k = 0;
        while(k < r && g == 1){
          q = mr.generate(q);
          y = mr.generate(y);
          ys = y;
          for(int i = 0; i < std::min(m, r - k); i++){
            y = f(y);
            unsigned long long z = mr.reduce(y);
            q = mr.mul(q, mr.generate(x > z ? x - z : z - x));
          }
          y = mr.reduce(y);
          g = binary_gcd(mr.reduce(q), n);
          k += m;
        }
        r <<= 1;
      }while(g == 1);
      if(g == n){
        do{
          ys = f(ys);
          unsigned long long z = mr.reduce(ys);
          g = binary_gcd(x > z ? x - z : z - x, n);
        }while(g == 1);
      }
      return g; // g == n when failure
    };
    unsigned long long c = 1, res = n;
    do{
      res = try_factorize(c);
      // c = generate_random_prime(2, n - 1);
      c = (c + 1) % n;
    }while(res == n);
    return res;
  }
  std::vector<unsigned long long> factorize(unsigned long long n){
    if(n <= 1) return {};
    unsigned long long x = rho(n);
    if(x == n) return {x};
    auto l = factorize(x);
    auto r = factorize(n / x);
    l.insert(l.end(), r.begin(), r.end());
    return l;
  }
  // {素数, 個数}の形で返す
  std::vector<std::pair<unsigned long long, int>> factorize2(unsigned long long n){
    auto p = factorize(n);
    sort(p.begin(), p.end());
    std::vector<std::pair<unsigned long long, int>> ret;
    for(int i : p){
      if(ret.empty() || ret.back().first != i) ret.push_back({i, 1});
      else ret.back().second++;
    }
    return ret;
  }
  // 素因数の集合(重複なし, ソート済)を返す
  std::vector<unsigned long long> prime_factor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());
    p.erase(std::unique(p.begin(), p.end()), p.end());
    return p;
  }
  // 10^18以下の高度合成数 897612484786617600の約数が103680個なので全列挙して良さそう
  std::vector<unsigned long long> divisor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());

    std::vector<std::pair<unsigned long long, int>> x;

    for(int i = 0; i < p.size(); i++){
      if(!i || p[i] != p[i - 1]) x.push_back({p[i], 1});
      else x.back().second++;
    }
    int sz = 1;
    for(auto [p_cur, cnt] : x) sz *= cnt + 1;

    std::vector<unsigned long long> res(sz);
    res[0] = 1;
    int r_prev = 1, r = 1;
    for(auto [p_cur, cnt] : x){
      unsigned long long ppow = 1;
      for(int c = 0; c < cnt; c++){
        ppow *= p_cur;
        for(int i = 0; i < r_prev; i++){
          res[r++] = res[i] * ppow;
        }
      }
      r_prev = r;
    }
    return res;
  }
  int mobius_function(long long x){
    auto P = rho_factorization::factorize(x);
    for(long long p : P) if((x / p) % p == 0) return 0;
    return P.size() % 2 == 0 ? 1 : -1;
  }
  unsigned long long totient_function(unsigned long long n){
    unsigned long long res = n;
    auto prims = rho_factorization::prime_factor(n);
    for(auto p : prims) res -= res / p;
    return res;
  }
};
// p: 素数
unsigned long long find_primitive_root(unsigned long long p){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  //assert(miller_rabin_mr(p));
  auto primes = rho_factorization::prime_factor(p - 1);
  while(true){
    bool f = true;
    unsigned long long a = engine() % (p - 1) + 1;
    for(unsigned long long pk : primes){
      // a ^ (p - 1) / pk ≡ 1 (mod p) -> no
      if(mod_pow_mr(a, (p - 1) / pk, p) == 1){
        f = false;
        break;
      }
    }
    if(f) return a;
  }
}
using mint = dynamic_modint<0>;

int main(){
  int p, t;
  std::cin >> p >> t;
  mint::set_mod(p);
  int kon = find_primitive_root(p);
  vector<int> N, G, X;
  range(i, 0, t){
    int n;
    std::cin >> n;
    N.push_back(n);
    range(j, 0, n){
      int g;
      std::cin >> g;
      G.push_back(g);
    }
    int x;
    std::cin >> x;
    X.push_back(x);
  }
  range(i, 0, t) G.push_back(X[i]);

  accumulate1d<int> Nac(N);
  auto b = bsgs_many<mint>(kon, G);
  int q = p - 1;
  range(i, 0, t){
    int lid = Nac.query(0, i);
    int rid = lid + N[i];
    int g_ = q;
    range(j, lid, rid) g_ = gcd(g_, b[j]);
    int d = b[Nac.query(0, t) + i];
    if(d % g_ == 0){
      std::cout << 1 << '\n';
    }else{
      std::cout << 0 << '\n';
    }
  }
}
accuracy: 1
time_ms: 3060
memory_kb: 39432
final_rank: 13

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <array>
#include <tuple>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <bitset>
#include <cmath>
#include <functional>
#include <cassert>
#include <climits>
#include <iomanip>
#include <numeric>
#include <memory>
#include <random>
#include <thread>
#include <chrono>
#define allof(obj) (obj).begin(), (obj).end()
#define range(i, l, r) for(int i=l;i<r;i++)
#define unique_elem(obj) obj.erase(std::unique(allof(obj)), obj.end())
#define bit_subset(i, S) for(int i=S, zero_cnt=0;(zero_cnt+=i==S)<2;i=(i-1)&S)
#define bit_kpop(i, n, k) for(int i=(1<<k)-1,x_bit,y_bit;i<(1<<n);x_bit=(i&-i),y_bit=i+x_bit,i=(!i?(1<<n):((i&~y_bit)/x_bit>>1)|y_bit))
#define bit_kth(i, k) ((i >> k)&1)
#define bit_highest(i) (i?63-__builtin_clzll(i):-1)
#define bit_lowest(i) (i?__builtin_ctzll(i):-1)
#define sleepms(t) std::this_thread::sleep_for(std::chrono::milliseconds(t))
using ll = long long;
using ld = long double;
using ul = uint64_t;
using pi = std::pair<int, int>;
using pl = std::pair<ll, ll>;
using namespace std;

template<typename F, typename S>
std::ostream &operator<<(std::ostream &dest, const std::pair<F, S> &p){
  dest << p.first << ' ' << p.second;
  return dest;
}
template<typename T>
std::ostream &operator<<(std::ostream &dest, const std::vector<T> &v){
  int sz = v.size();
  if(sz==0) return dest;
  for(int i=0;i<sz-1;i++) dest << v[i] << ' ';
  dest << v[sz-1];
  return dest;
}
template<typename T>
vector<T> read_vec(size_t sz){
  std::vector<T> v(sz);
  for(int i=0;i<(int)sz;i++) std::cin >> v[i];
  return v;
}
template<typename T, typename... Tail>
auto read_vec(size_t sz, Tail ...tail){
  auto v = std::vector<decltype(read_vec<T>(tail...))>(sz);
  for(int i=0;i<(int)sz;i++) v[i] = read_vec<T>(tail...);
  return v;
}
void io_init(){
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}
template<typename Val>
struct accumulate1d{
  std::vector<Val> sum;
  accumulate1d(){}
  accumulate1d(const std::vector<Val> &v): sum(v){
    for(int i = 1; i < v.size(); i++) sum[i] = sum[i - 1] + v[i];
  }
  // [0, r)の和, 範囲外の部分は全て単位元
  Val query(int r){
    r = std::min(r, (int)sum.size());
    if(r <= 0) return 0;
    return sum[r - 1];
  }
  // [l, r)の和, 範囲外の部分は全て単位元
  Val query(int l, int r){
    l = std::max(l, 0);
    r = std::min(r, (int)sum.size());
    if(r <= l) return 0;
    return (l == 0 ? sum[r - 1] : (sum[r - 1] - sum[l - 1]));
  }
  void push_back(Val x){
    Val y = (sum.empty() ? 0 : sum.back());
    sum.push_back(y + x);
  }
  void pop_back(){
    assert(!sum.empty());
    sum.pop_back();
  }
  // [0, k]がx以上になる最小インデックス, ない場合はn
  int lower_bound(Val x){
    return std::lower_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
  // [0, k]がxより大きくなる最小インデックス, ない場合はn
  int upper_bound(Val x){
    return std::upper_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
};



#include <type_traits>
#include <ostream>


// @param m `1 <= m`
constexpr long long safe_mod(long long x, long long m){
  x %= m;
  if (x < 0) x += m;
  return x;
}
struct barrett{
  unsigned int _m;
  unsigned long long im;
  explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1){}
  unsigned int umod()const{return _m;}
  unsigned int mul(unsigned int a, unsigned int b)const{
    unsigned long long z = a;
    z *= b;
#ifdef _MSC_VER
    unsigned long long x;
    _umul128(z, im, &x);
#else
    unsigned long long x = (unsigned long long)(((unsigned __int128)(z) * im) >> 64);
#endif
    unsigned long long y = x * _m;
    return (unsigned int)(z - y + (z < y ? _m : 0));
  }
};
// @param n `0 <= n`
// @param m `1 <= m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m){
  if(m == 1) return 0;
  unsigned int _m = (unsigned int)(m);
  unsigned long long r = 1;
  unsigned long long y = safe_mod(x, m);
  while(n){
    if (n & 1) r = (r * y) % _m;
    y = (y * y) % _m;
    n >>= 1;
  }
  return r;
}
constexpr bool is_prime_constexpr(int n) {
  if (n <= 1) return false;
  if (n == 2 || n == 7 || n == 61) return true;
  if (n % 2 == 0) return false;
  long long d = n - 1;
  while (d % 2 == 0) d /= 2;
  constexpr long long bases[3] = {2, 7, 61};
  for(long long a : bases){
    long long t = d;
    long long y = pow_mod_constexpr(a, t, n);
    while(t != n - 1 && y != 1 && y != n - 1){
      y = y * y % n;
      t <<= 1;
    }
    if(y != n - 1 && t % 2 == 0){
      return false;
    }
  }
  return true;
}
template<int n>
constexpr bool is_prime = is_prime_constexpr(n);

constexpr int primitive_root_constexpr(int m){
  if(m == 2) return 1;
  if(m == 167772161) return 3;
  if(m == 469762049) return 3;
  if(m == 754974721) return 11;
  if(m == 998244353) return 3;
  int divs[20] = {};
  divs[0] = 2;
  int cnt = 1;
  int x = (m - 1) / 2;
  while (x % 2 == 0) x /= 2;
  for(int i = 3; (long long)(i)*i <= x; i += 2){
    if(x % i == 0){
      divs[cnt++] = i;
      while(x % i == 0){
        x /= i;
      }
    }
  }
  if(x > 1) divs[cnt++] = x;
  for(int g = 2;; g++){
    bool ok = true;
    for(int i = 0; i < cnt; i++){
      if(pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1){
        ok = false;
        break;
      }
    }
    if(ok)return g;
  }
}
template <int m>
constexpr int primitive_root = primitive_root_constexpr(m);

int ceil_pow2(int n){
  int x = 0;
  while ((1U << x) < (unsigned int)(n)) x++;
  return x;
}
int bsf(unsigned int n){
  return __builtin_ctz(n);
}
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b){
  a = safe_mod(a, b);
  if(a == 0) return {b, 0};
  long long s = b, t = a;
  long long m0 = 0, m1 = 1;
  while (t){
    long long u = s / t;
    s -= t * u;
    m0 -= m1 * u;
    auto tmp = s;
    s = t;
    t = tmp;
    tmp = m0;
    m0 = m1;
    m1 = tmp;
  }
  if(m0 < 0) m0 += b / s;
  return {s, m0};
}



template<int m>
long long modpow(long long a, long long b){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}
// @param 0 <= b, 0 < m
long long modpow(long long a, long long b, int m){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}

struct modint_base {};

template<int id> 
struct dynamic_modint : modint_base{
  using mint = dynamic_modint;
public:
  static int mod(){return (int)(bt.umod());}
  static void set_mod(int m){
    assert(1 <= m);
    bt = barrett(m);
  }
  static mint raw(int v){
    mint x;
    x._v = v;
    return x;
  }
  dynamic_modint(): _v(0){}
  template <class T>
  dynamic_modint(T v){
    long long x = v % (long long)(mod());
    if (x < 0) x += mod();
    _v = x;
  }
  unsigned int val()const{return _v;}
  mint& operator++(){
    _v++;
    if(_v == umod()) _v = 0;
    return *this;
  }
  mint& operator--(){
    if (_v == 0) _v = umod();
    _v--;
    return *this;
  }
  mint operator++(int){
    mint result = *this;
    ++*this;
    return result;
  }
  mint operator--(int){
    mint result = *this;
    --*this;
    return result;
  }
  mint& operator+=(const mint& rhs){
    _v += rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator-=(const mint& rhs){
    _v += mod() - rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator*=(const mint& rhs){
    _v = bt.mul(_v, rhs._v);
    return *this;
  }
  mint& operator/=(const mint& rhs){return *this = *this * rhs.inv();}
  mint operator+()const{return *this;}
  mint operator-()const{return mint() - *this;}
  mint pow(long long n)const{
    assert(0 <= n);
    mint x = *this, r = 1;
    while(n){
      if (n & 1) r *= x;
      x *= x;
      n >>= 1;
    }
    return r;
  }
  mint inv()const{
    auto eg = inv_gcd(_v, mod());
    assert(eg.first == 1);
    return eg.second;
  }
  friend mint operator+(const mint& lhs, const mint& rhs){return mint(lhs) += rhs;}
  friend mint operator-(const mint& lhs, const mint& rhs){return mint(lhs) -= rhs;}
  friend mint operator*(const mint& lhs, const mint& rhs){return mint(lhs) *= rhs;}
  friend mint operator/(const mint& lhs, const mint& rhs){return mint(lhs) /= rhs;}
  friend bool operator==(const mint& lhs, const mint& rhs){return lhs._v == rhs._v;}
  friend bool operator!=(const mint& lhs, const mint& rhs){return lhs._v != rhs._v;}
private:
  unsigned int _v;
  static barrett bt;
  static unsigned int umod(){return bt.umod();}
};
template <int id>
barrett dynamic_modint<id>::bt(998244353);
using modint = dynamic_modint<-1>;
template<int id>
std::ostream &operator<<(std::ostream &dest, const dynamic_modint<id> &a){
  dest << a.val();
  return dest;
}
#include <limits>
// 符号なし整数 -> 符号付き整数
template <class T>
using make_signed_t = typename std::make_signed<T>::type;
// 符号付き整数 -> 符号なし整数
template <class T>
using make_unsigned_t = typename std::make_unsigned<T>::type;
// 符号付き32bit整数か
template <class T>
using is_signed_int32 = typename std::conditional<std::is_same<T, int>::value || std::is_same<T, int32_t>::value, std::true_type, std::false_type>::type;
// 符号なし32bit整数か
template <class T>
using is_unsigned_int32 = typename std::conditional<std::is_same<T, unsigned int>::value || std::is_same<T, uint32_t>::value, std::true_type, std::false_type>::type;
// 符号付き64bit整数か
template <class T>
using is_signed_int64 = typename std::conditional<std::is_same<T, long long int>::value || std::is_same<T, int64_t>::value, std::true_type, std::false_type>::type;
// 符号なし64bit整数か
template <class T>
using is_unsigned_int64 = typename std::conditional<std::is_same<T, unsigned long long>::value || std::is_same<T, uint64_t>::value, std::true_type, std::false_type>::type;
// 符号付き128bit整数か
template <class T>
using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type;
// 符号なし128bit整数か
template <class T>
using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 128bit整数か
template <class T>
using is_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value || std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの整数か
template<class T>
using is_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value || is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号付き整数か
template<class T>
using is_signed_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号なし整数か
template<class T>
using is_unsigned_intle64 = typename std::conditional<is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;

template<class T>
using is_not_t = typename std::conditional<T::value, std::false_type, std::true_type>::type;

unsigned long long random_once(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  static unsigned long long ret = engine();
  return ret;
}

unsigned long long random_number(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  return engine();
}

// [low, high]
unsigned long long random_number(unsigned long long low, unsigned long long high){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  assert(high >= low);
  unsigned long long diff = high - low + 1;
  return engine() % diff + low;
}
unsigned long long ceillog2(unsigned long long x){
  int res = 1;
  while((1ULL << res) < x) res++;
  return res;
}

// uint32 : uKey ∈ [0, 2^31 - 1)
// uint64 : uKey ∈ [0, 2^63 - 1)
template<typename uKey, typename Val>
struct uhash_map{
  static_assert(is_unsigned_intle64<uKey>::value, "uKey must be unsigned integer (32 or 64bit)");
private:
  using Key = typename std::make_signed<uKey>::type;
  static constexpr int initial_size = 8; // 指定しなかった場合の初期サイズ
  static constexpr float alpha = 0.7; // 占有率がこれを超えると再構築
  static constexpr Key null_val = std::numeric_limits<Key>::min();
  static constexpr Key inf = std::numeric_limits<Key>::max();
  static const unsigned long long r;
  int table_size, table_size_mod;
  int occupied_cnt, elem_cnt; // 使われている要素の数, そのうちまだ消されていない要素の数
  std::vector<std::pair<Key, Val>> v;
  size_t hash(unsigned long long x){
    x += r;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return (x ^ (x >> 31)) & table_size_mod;
  }
  void expand(){
    std::vector<std::pair<Key, Val>> tmp(elem_cnt, {null_val, Val()});
    for(int i = 0, j = 0; i < table_size; i++) if(v[i].first >= 0) tmp[j++] = v[i];
    occupied_cnt = elem_cnt = 0;
    table_size <<= 1;
    table_size_mod = table_size - 1;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
    for(int i = 0; i < tmp.size(); i++) emplace_inner(tmp[i].first, tmp[i].second);
  }
  void emplace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        if(v[i].first == -x - 1){
          elem_cnt++;
          v[i] = {x, y};
        }
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void emplace_replace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt += (v[i].first == -x - 1);
        v[i] = {x, y};
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void erase_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return;
      else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt -= (v[i].first == x);
        v[i].first = -x - 1;
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  bool find_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return false;
      else if(v[i].first == x || v[i].first == -x - 1) return v[i].first == x;
      i = (i + 1) & table_size_mod;
    }
  }
  std::pair<bool, Val> at_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return std::make_pair(false, v[i].second);
      else if(v[i].first == x || v[i].first == -x - 1) return (v[i].first == x ? std::make_pair(true, v[i].second) : std::make_pair(false, v[i].second));
      i = (i + 1) & table_size_mod;
    }
  }
public:
  uhash_map(): table_size(initial_size), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  uhash_map(int _sz): table_size(1 << ceillog2(_sz)), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  // 追加, すでにある場合は無視
  void emplace(uKey x, Val y){
    assert(x < inf);
    emplace_inner(x, y);
  }
  // 追加, すでにある場合は置き換える
  void emplace_replace(uKey x, Val y){
    assert(x < inf);
    emplace_replace_inner(x, y);
  }
  // 削除, 無い場合は無視
  void erase(uKey x){
    assert(x < inf);
    erase_inner(x);
  }
  // 検索
  bool find(uKey x){
    assert(x < inf);
    return find_inner(x);
  }
  // 存在するか, 存在する場合その値
  std::pair<bool, Val> at(uKey x){
    assert(x < inf);
    return at_inner(x);
  }
  int size(){
    return elem_cnt;
  }
  bool empty(){
    return elem_cnt == 0;
  }
  std::vector<std::pair<uKey, Val>> enumerate(){
    std::vector<std::pair<uKey, Val>> res;
    for(int i = 0; i < table_size; i++) if(v[i].first >= 0) res.push_back(v[i]);
    return res;
  }
  void clear(){
    table_size = initial_size;
    table_size_mod = table_size - 1;
    occupied_cnt = elem_cnt = 0;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
  }
};
template<typename uKey, typename Val>
const unsigned long long uhash_map<uKey, Val>::r = random_number();
// 素数m, 数列A, bを与える
// 各a_iに対してb ^ k ≡ a_iを満たすkを返す
template<typename mint>
std::vector<int> bsgs_many(int b, const std::vector<int> &A){
  int init_size = 2e6; // mod998244353, |A| = 2e5で設定 メモリ130MB |A|が大きい場合は1e7などにする 
  init_size = std::min(init_size, mint::mod());
  // 前処理 O(init_size)
  uhash_map<unsigned, int> mp(init_size * 2);
  mint x = 1;
  for(int i = 0; i < init_size; i++){
    mp.emplace(x.val(), i);
    x *= b;
  }
  std::vector<int> res;
  int imax = (mint::mod() + init_size - 1) / init_size;
  mint y = mint(b).pow((long long)2 * mint::mod() - 2 - init_size); // b ^ {-init_size}
  // 計算 O(|A| * mod / init_size)
  for(int a : A){
    x = a;
    for(int i = 0; i < imax; i++){
      auto [f, j] = mp.at(x.val());
      if(f){
        res.push_back(i * init_size + j);
        break;
      }
      x *= y;
    }
  }
  return res;
}
#include <cstdint>

struct barrett_reduction{
  unsigned int mod;
  unsigned long long m;
  barrett_reduction(unsigned int _mod) : mod(_mod){
    m = ((__uint128_t)1 << 64) / mod;
  }
  unsigned int reduce(unsigned int a){
    unsigned long long q = ((__uint128_t)a * m) >> 64;
    a -= q * mod; // 0 <= a < 2 * mod
    // return a;
    return a >= mod ? a - mod : a;
  }
  unsigned int mul(unsigned int a, unsigned int b){
    return reduce((unsigned long long)a * b);
  }
  // {gcd(a, mod), x}, such that a * x ≡ gcd(a, mod)
  std::pair<unsigned int, unsigned int> inv(unsigned int a){
    if(a >= mod) a = reduce(a);
    if(a == 0) return {mod, 0};
    unsigned int s = mod, t = a;
    long long m0 = 0, m1 = 1;
    while(t){
      int u = s / t;
      s -= t * u;
      m0 -= m1 * u;
      std::swap(m0, m1);
      std::swap(s, t);
    }
    if(m0 < 0) m0 += mod / s;
    return {s, m0};
  }
};
// 64bit mod対応
// R = 2^64
// 偶数modだと壊れる
struct montgomery_reduction_64bit{
private:
  // [0, 2 * MOD)
  inline uint64_t reduce_unsafe(__uint128_t x) const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x;
  }
  void _set_mod(uint64_t mod){
    assert((mod < (1ULL << 63)) && (mod & 1));
    MOD = mod;
    NEG_INV = 0;
    __uint128_t s = 1, t = 0;
    for(int i = 0; i < 64; i++){
      if (~t & 1) {
        t += MOD;
        NEG_INV += s;
      }
      t >>= 1;
      s <<= 1;
    }
    R2 = ((__uint128_t)1 << 64) % MOD;
    R2 = R2 * R2 % MOD;
    ONE = generate(1);
  }
  __uint128_t MOD, NEG_INV, R2;
  uint64_t ONE;
public:
  montgomery_reduction_64bit(){}
  montgomery_reduction_64bit(uint64_t mod){_set_mod(mod);}
  void set_mod(uint64_t mod){
    _set_mod(mod);
  }
  uint64_t mod()const{
    return MOD;
  }
  inline uint64_t one()const{
    return ONE;
  }
  inline uint64_t generate(uint64_t x)const{
    return reduce((__uint128_t)x * R2);
  }
  inline uint64_t reduce(__uint128_t x)const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x < MOD ? x : x - MOD;
  }
  inline uint64_t fix(uint64_t x)const{
    return x < MOD ? x : x - MOD;
  }
  // [0, 2MOD)
  inline uint64_t mul(uint64_t mx, uint64_t my)const{
    return reduce_unsafe((__uint128_t)mx * my);
  }
  inline uint64_t mul_safe(uint64_t mx, uint64_t my)const{
    return reduce((__uint128_t)mx * my);
  }
  // [0, 2MOD)
  inline uint64_t add(uint64_t mx, uint64_t my)const{
    return (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
  }
  inline uint64_t add_safe(uint64_t mx, uint64_t my)const{
    uint64_t res = (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
    return res >= MOD ? res - MOD : res;
  }
  // [0, 2MOD)
  inline uint64_t sub(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    return mx >= my ? mx - my : mx + MOD - my;
  }
  inline uint64_t sub_safe(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    uint64_t res = mx >= my ? mx - my : mx + MOD - my;
    return res >= MOD ? res - MOD : res;
  }
  inline uint64_t pow(uint64_t ma, uint64_t b)const{
    uint64_t ret = one();
    while(b){
      if(b & 1) ret = mul(ret, ma);
      ma = mul(ma, ma);
      b >>= 1;
    }
    return ret;
  }
  inline uint64_t pow_safe(uint64_t ma, uint64_t b)const{
    return fix(pow(ma, b));
  }
};
unsigned long long mod_pow_mr(unsigned long long a, unsigned long long b, unsigned long long m){
  montgomery_reduction_64bit mr(m);
  return mr.reduce(mr.pow(mr.generate(a), b));
}
bool _miller_rabin_mr(unsigned long long n, const montgomery_reduction_64bit &mr){
  static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
  static std::vector<unsigned long long> A{2, 325, 9375, 28178, 450775, 9780504, 1795265022};
  static std::vector<unsigned long long> B{2, 7, 61};
  if(n <= 1) return false;
  if(n <= 50){
    for(int l = n < 20 ? 0 : 8, r = n < 20 ? 8 : 15; l < r; l++) if(small_p[l] == n) return true;
    return false;
  }
  if(!(n & 1)) return false;
  unsigned long long d = n - 1;
  unsigned long long one = mr.one(), mone = mr.generate(n - 1);
  d >>= __builtin_ctzll(d);
  for(unsigned long long a : (n >> 32) ? A : B){
    if(a % n == 0) continue;
    unsigned long long d2s = d; // d * 2^s, 0 <= s <= (n - 1)が2で割れる回数
    unsigned long long y = mr.pow_safe(mr.generate(a), d);
    while(d2s != n - 1 && y != one && y != mone){
      y = mr.mul_safe(y, y);
      d2s <<= 1;
    }
    if(y != mone && !(d2s & 1)) return false;
  }
  return true;
}
bool miller_rabin_mr(unsigned long long n){
  if(n % 2 == 0) return n == 2 ? true : false;
  montgomery_reduction_64bit mr(n);
  return _miller_rabin_mr(n, mr);
}
// https://en.wikipedia.org/wiki/Binary_GCD_algorithm
unsigned long long binary_gcd(unsigned long long a, unsigned long long b){
  if(!a || !b) return !a ? b : a;
  int shift = __builtin_ctzll(a | b); // [1] gcd(2a', 2b') = 2 * gcd(a', b')
  a >>= __builtin_ctzll(a);
  do{
    // if b is odd
    // gcd(2a', b) = gcd(a', b), if a = 2a'(a is even)
    // gcd(a, b) = gcd(|a - b|, min(a, b)), if a is odd
    b >>= __builtin_ctzll(b); // make b odd
    if(a > b) std::swap(a, b);
    b -= a;
  }while(b); // gcd(a, 0) = a
  return a << shift; // [1]
}
unsigned long long generate_random_prime(unsigned long long min_n = 2, unsigned long long max_n = ~0ULL){
  std::random_device seed_gen;
  std::mt19937_64 engine(seed_gen());
  __uint128_t len = max_n - min_n + 1;
  // https://en.wikipedia.org/wiki/Prime_number_theorem
  while(true){
    unsigned long long a = engine() % len + min_n;
    if(miller_rabin_mr(a)){
      return a;
    }
  }
}
namespace rho_factorization{
  unsigned long long rho(unsigned long long n){
    static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};

    for(int sp : small_p) if(n % sp == 0) return sp; // n < 50

    montgomery_reduction_64bit mr(n);
    if(_miller_rabin_mr(n, mr)) return n;

    auto try_factorize = [n, mr](unsigned long long c){
      c = mr.generate(c);
      auto f = [mr, c](unsigned long long mx){
        return mr.add(mr.mul(mx, mx), c);
      };
      unsigned long long m = 1LL << ((64 - __builtin_clzll(n)) / 8);
      unsigned long long y = n, r = 1, q = 1;
      unsigned long long x, g, k, ys;
      do{
        x = y;
        y = mr.generate(y);
        for(int i = 0; i < r; i++) y = f(y);
        y = mr.reduce(y);

        k = 0;
        while(k < r && g == 1){
          q = mr.generate(q);
          y = mr.generate(y);
          ys = y;
          for(int i = 0; i < std::min(m, r - k); i++){
            y = f(y);
            unsigned long long z = mr.reduce(y);
            q = mr.mul(q, mr.generate(x > z ? x - z : z - x));
          }
          y = mr.reduce(y);
          g = binary_gcd(mr.reduce(q), n);
          k += m;
        }
        r <<= 1;
      }while(g == 1);
      if(g == n){
        do{
          ys = f(ys);
          unsigned long long z = mr.reduce(ys);
          g = binary_gcd(x > z ? x - z : z - x, n);
        }while(g == 1);
      }
      return g; // g == n when failure
    };
    unsigned long long c = 1, res = n;
    do{
      res = try_factorize(c);
      // c = generate_random_prime(2, n - 1);
      c = (c + 1) % n;
    }while(res == n);
    return res;
  }
  std::vector<unsigned long long> factorize(unsigned long long n){
    if(n <= 1) return {};
    unsigned long long x = rho(n);
    if(x == n) return {x};
    auto l = factorize(x);
    auto r = factorize(n / x);
    l.insert(l.end(), r.begin(), r.end());
    return l;
  }
  // {素数, 個数}の形で返す
  std::vector<std::pair<unsigned long long, int>> factorize2(unsigned long long n){
    auto p = factorize(n);
    sort(p.begin(), p.end());
    std::vector<std::pair<unsigned long long, int>> ret;
    for(int i : p){
      if(ret.empty() || ret.back().first != i) ret.push_back({i, 1});
      else ret.back().second++;
    }
    return ret;
  }
  // 素因数の集合(重複なし, ソート済)を返す
  std::vector<unsigned long long> prime_factor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());
    p.erase(std::unique(p.begin(), p.end()), p.end());
    return p;
  }
  // 10^18以下の高度合成数 897612484786617600の約数が103680個なので全列挙して良さそう
  std::vector<unsigned long long> divisor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());

    std::vector<std::pair<unsigned long long, int>> x;

    for(int i = 0; i < p.size(); i++){
      if(!i || p[i] != p[i - 1]) x.push_back({p[i], 1});
      else x.back().second++;
    }
    int sz = 1;
    for(auto [p_cur, cnt] : x) sz *= cnt + 1;

    std::vector<unsigned long long> res(sz);
    res[0] = 1;
    int r_prev = 1, r = 1;
    for(auto [p_cur, cnt] : x){
      unsigned long long ppow = 1;
      for(int c = 0; c < cnt; c++){
        ppow *= p_cur;
        for(int i = 0; i < r_prev; i++){
          res[r++] = res[i] * ppow;
        }
      }
      r_prev = r;
    }
    return res;
  }
  int mobius_function(long long x){
    auto P = rho_factorization::factorize(x);
    for(long long p : P) if((x / p) % p == 0) return 0;
    return P.size() % 2 == 0 ? 1 : -1;
  }
  unsigned long long totient_function(unsigned long long n){
    unsigned long long res = n;
    auto prims = rho_factorization::prime_factor(n);
    for(auto p : prims) res -= res / p;
    return res;
  }
};
// p: 素数
unsigned long long find_primitive_root(unsigned long long p){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  //assert(miller_rabin_mr(p));
  auto primes = rho_factorization::prime_factor(p - 1);
  while(true){
    bool f = true;
    unsigned long long a = engine() % (p - 1) + 1;
    for(unsigned long long pk : primes){
      // a ^ (p - 1) / pk ≡ 1 (mod p) -> no
      if(mod_pow_mr(a, (p - 1) / pk, p) == 1){
        f = false;
        break;
      }
    }
    if(f) return a;
  }
}
using mint = dynamic_modint<0>;

int main(){
  int p, t;
  std::cin >> p >> t;
  mint::set_mod(p);
  int kon = find_primitive_root(p);
  vector<int> N, G, X;
  range(i, 0, t){
    int n;
    std::cin >> n;
    N.push_back(n);
    range(j, 0, n){
      int g;
      std::cin >> g;
      G.push_back(g);
    }
    int x;
    std::cin >> x;
    X.push_back(x);
  }
  range(i, 0, t) G.push_back(X[i]);

  accumulate1d<int> Nac(N);
  auto b = bsgs_many<mint>(kon, G);
  int q = p - 1;
  range(i, 0, t){
    int lid = Nac.query(0, i);
    int rid = lid + N[i];
    int g_ = q;
    range(j, lid, rid) g_ = gcd(g_, b[j]);
    int d = b[Nac.query(0, t) + i];
    if(d % g_ == 0){
      std::cout << 1 << '\n';
    }else{
      std::cout << 0 << '\n';
    }
  }
}
accuracy: 0.3088235294117647
time_ms: 2040
memory_kb: 39196
final_rank: 15

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <array>
#include <tuple>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <bitset>
#include <cmath>
#include <functional>
#include <cassert>
#include <climits>
#include <iomanip>
#include <numeric>
#include <memory>
#include <random>
#include <thread>
#include <chrono>
#define allof(obj) (obj).begin(), (obj).end()
#define range(i, l, r) for(int i=l;i<r;i++)
#define unique_elem(obj) obj.erase(std::unique(allof(obj)), obj.end())
#define bit_subset(i, S) for(int i=S, zero_cnt=0;(zero_cnt+=i==S)<2;i=(i-1)&S)
#define bit_kpop(i, n, k) for(int i=(1<<k)-1,x_bit,y_bit;i<(1<<n);x_bit=(i&-i),y_bit=i+x_bit,i=(!i?(1<<n):((i&~y_bit)/x_bit>>1)|y_bit))
#define bit_kth(i, k) ((i >> k)&1)
#define bit_highest(i) (i?63-__builtin_clzll(i):-1)
#define bit_lowest(i) (i?__builtin_ctzll(i):-1)
#define sleepms(t) std::this_thread::sleep_for(std::chrono::milliseconds(t))
using ll = long long;
using ld = long double;
using ul = uint64_t;
using pi = std::pair<int, int>;
using pl = std::pair<ll, ll>;
using namespace std;

template<typename F, typename S>
std::ostream &operator<<(std::ostream &dest, const std::pair<F, S> &p){
  dest << p.first << ' ' << p.second;
  return dest;
}
template<typename T>
std::ostream &operator<<(std::ostream &dest, const std::vector<T> &v){
  int sz = v.size();
  if(sz==0) return dest;
  for(int i=0;i<sz-1;i++) dest << v[i] << ' ';
  dest << v[sz-1];
  return dest;
}
template<typename T>
vector<T> read_vec(size_t sz){
  std::vector<T> v(sz);
  for(int i=0;i<(int)sz;i++) std::cin >> v[i];
  return v;
}
template<typename T, typename... Tail>
auto read_vec(size_t sz, Tail ...tail){
  auto v = std::vector<decltype(read_vec<T>(tail...))>(sz);
  for(int i=0;i<(int)sz;i++) v[i] = read_vec<T>(tail...);
  return v;
}
void io_init(){
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}
template<typename Val>
struct accumulate1d{
  std::vector<Val> sum;
  accumulate1d(){}
  accumulate1d(const std::vector<Val> &v): sum(v){
    for(int i = 1; i < v.size(); i++) sum[i] = sum[i - 1] + v[i];
  }
  // [0, r)の和, 範囲外の部分は全て単位元
  Val query(int r){
    r = std::min(r, (int)sum.size());
    if(r <= 0) return 0;
    return sum[r - 1];
  }
  // [l, r)の和, 範囲外の部分は全て単位元
  Val query(int l, int r){
    l = std::max(l, 0);
    r = std::min(r, (int)sum.size());
    if(r <= l) return 0;
    return (l == 0 ? sum[r - 1] : (sum[r - 1] - sum[l - 1]));
  }
  void push_back(Val x){
    Val y = (sum.empty() ? 0 : sum.back());
    sum.push_back(y + x);
  }
  void pop_back(){
    assert(!sum.empty());
    sum.pop_back();
  }
  // [0, k]がx以上になる最小インデックス, ない場合はn
  int lower_bound(Val x){
    return std::lower_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
  // [0, k]がxより大きくなる最小インデックス, ない場合はn
  int upper_bound(Val x){
    return std::upper_bound(sum.begin(), sum.end(), x) - sum.begin();
  }
};



#include <type_traits>
#include <ostream>


// @param m `1 <= m`
constexpr long long safe_mod(long long x, long long m){
  x %= m;
  if (x < 0) x += m;
  return x;
}
struct barrett{
  unsigned int _m;
  unsigned long long im;
  explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1){}
  unsigned int umod()const{return _m;}
  unsigned int mul(unsigned int a, unsigned int b)const{
    unsigned long long z = a;
    z *= b;
#ifdef _MSC_VER
    unsigned long long x;
    _umul128(z, im, &x);
#else
    unsigned long long x = (unsigned long long)(((unsigned __int128)(z) * im) >> 64);
#endif
    unsigned long long y = x * _m;
    return (unsigned int)(z - y + (z < y ? _m : 0));
  }
};
// @param n `0 <= n`
// @param m `1 <= m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m){
  if(m == 1) return 0;
  unsigned int _m = (unsigned int)(m);
  unsigned long long r = 1;
  unsigned long long y = safe_mod(x, m);
  while(n){
    if (n & 1) r = (r * y) % _m;
    y = (y * y) % _m;
    n >>= 1;
  }
  return r;
}
constexpr bool is_prime_constexpr(int n) {
  if (n <= 1) return false;
  if (n == 2 || n == 7 || n == 61) return true;
  if (n % 2 == 0) return false;
  long long d = n - 1;
  while (d % 2 == 0) d /= 2;
  constexpr long long bases[3] = {2, 7, 61};
  for(long long a : bases){
    long long t = d;
    long long y = pow_mod_constexpr(a, t, n);
    while(t != n - 1 && y != 1 && y != n - 1){
      y = y * y % n;
      t <<= 1;
    }
    if(y != n - 1 && t % 2 == 0){
      return false;
    }
  }
  return true;
}
template<int n>
constexpr bool is_prime = is_prime_constexpr(n);

constexpr int primitive_root_constexpr(int m){
  if(m == 2) return 1;
  if(m == 167772161) return 3;
  if(m == 469762049) return 3;
  if(m == 754974721) return 11;
  if(m == 998244353) return 3;
  int divs[20] = {};
  divs[0] = 2;
  int cnt = 1;
  int x = (m - 1) / 2;
  while (x % 2 == 0) x /= 2;
  for(int i = 3; (long long)(i)*i <= x; i += 2){
    if(x % i == 0){
      divs[cnt++] = i;
      while(x % i == 0){
        x /= i;
      }
    }
  }
  if(x > 1) divs[cnt++] = x;
  for(int g = 2;; g++){
    bool ok = true;
    for(int i = 0; i < cnt; i++){
      if(pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1){
        ok = false;
        break;
      }
    }
    if(ok)return g;
  }
}
template <int m>
constexpr int primitive_root = primitive_root_constexpr(m);

int ceil_pow2(int n){
  int x = 0;
  while ((1U << x) < (unsigned int)(n)) x++;
  return x;
}
int bsf(unsigned int n){
  return __builtin_ctz(n);
}
// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b){
  a = safe_mod(a, b);
  if(a == 0) return {b, 0};
  long long s = b, t = a;
  long long m0 = 0, m1 = 1;
  while (t){
    long long u = s / t;
    s -= t * u;
    m0 -= m1 * u;
    auto tmp = s;
    s = t;
    t = tmp;
    tmp = m0;
    m0 = m1;
    m1 = tmp;
  }
  if(m0 < 0) m0 += b / s;
  return {s, m0};
}



template<int m>
long long modpow(long long a, long long b){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}
// @param 0 <= b, 0 < m
long long modpow(long long a, long long b, int m){
  assert(0 <= b);
  assert(0 < m);
  a = safe_mod(a, m);
  long long ret = 1;
  while(b){
    if(b & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ret;
}

struct modint_base {};

template<int id> 
struct dynamic_modint : modint_base{
  using mint = dynamic_modint;
public:
  static int mod(){return (int)(bt.umod());}
  static void set_mod(int m){
    assert(1 <= m);
    bt = barrett(m);
  }
  static mint raw(int v){
    mint x;
    x._v = v;
    return x;
  }
  dynamic_modint(): _v(0){}
  template <class T>
  dynamic_modint(T v){
    long long x = v % (long long)(mod());
    if (x < 0) x += mod();
    _v = x;
  }
  unsigned int val()const{return _v;}
  mint& operator++(){
    _v++;
    if(_v == umod()) _v = 0;
    return *this;
  }
  mint& operator--(){
    if (_v == 0) _v = umod();
    _v--;
    return *this;
  }
  mint operator++(int){
    mint result = *this;
    ++*this;
    return result;
  }
  mint operator--(int){
    mint result = *this;
    --*this;
    return result;
  }
  mint& operator+=(const mint& rhs){
    _v += rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator-=(const mint& rhs){
    _v += mod() - rhs._v;
    if(_v >= umod()) _v -= umod();
    return *this;
  }
  mint& operator*=(const mint& rhs){
    _v = bt.mul(_v, rhs._v);
    return *this;
  }
  mint& operator/=(const mint& rhs){return *this = *this * rhs.inv();}
  mint operator+()const{return *this;}
  mint operator-()const{return mint() - *this;}
  mint pow(long long n)const{
    assert(0 <= n);
    mint x = *this, r = 1;
    while(n){
      if (n & 1) r *= x;
      x *= x;
      n >>= 1;
    }
    return r;
  }
  mint inv()const{
    auto eg = inv_gcd(_v, mod());
    assert(eg.first == 1);
    return eg.second;
  }
  friend mint operator+(const mint& lhs, const mint& rhs){return mint(lhs) += rhs;}
  friend mint operator-(const mint& lhs, const mint& rhs){return mint(lhs) -= rhs;}
  friend mint operator*(const mint& lhs, const mint& rhs){return mint(lhs) *= rhs;}
  friend mint operator/(const mint& lhs, const mint& rhs){return mint(lhs) /= rhs;}
  friend bool operator==(const mint& lhs, const mint& rhs){return lhs._v == rhs._v;}
  friend bool operator!=(const mint& lhs, const mint& rhs){return lhs._v != rhs._v;}
private:
  unsigned int _v;
  static barrett bt;
  static unsigned int umod(){return bt.umod();}
};
template <int id>
barrett dynamic_modint<id>::bt(998244353);
using modint = dynamic_modint<-1>;
template<int id>
std::ostream &operator<<(std::ostream &dest, const dynamic_modint<id> &a){
  dest << a.val();
  return dest;
}
#include <limits>
// 符号なし整数 -> 符号付き整数
template <class T>
using make_signed_t = typename std::make_signed<T>::type;
// 符号付き整数 -> 符号なし整数
template <class T>
using make_unsigned_t = typename std::make_unsigned<T>::type;
// 符号付き32bit整数か
template <class T>
using is_signed_int32 = typename std::conditional<std::is_same<T, int>::value || std::is_same<T, int32_t>::value, std::true_type, std::false_type>::type;
// 符号なし32bit整数か
template <class T>
using is_unsigned_int32 = typename std::conditional<std::is_same<T, unsigned int>::value || std::is_same<T, uint32_t>::value, std::true_type, std::false_type>::type;
// 符号付き64bit整数か
template <class T>
using is_signed_int64 = typename std::conditional<std::is_same<T, long long int>::value || std::is_same<T, int64_t>::value, std::true_type, std::false_type>::type;
// 符号なし64bit整数か
template <class T>
using is_unsigned_int64 = typename std::conditional<std::is_same<T, unsigned long long>::value || std::is_same<T, uint64_t>::value, std::true_type, std::false_type>::type;
// 符号付き128bit整数か
template <class T>
using is_signed_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value, std::true_type, std::false_type>::type;
// 符号なし128bit整数か
template <class T>
using is_unsigned_int128 = typename std::conditional<std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 128bit整数か
template <class T>
using is_int128 = typename std::conditional<std::is_same<T, __int128_t>::value || std::is_same<T, __int128>::value || std::is_same<T, __uint128_t>::value || std::is_same<T, unsigned __int128>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの整数か
template<class T>
using is_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value || is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号付き整数か
template<class T>
using is_signed_intle64 = typename std::conditional<is_signed_int32<T>::value || is_signed_int64<T>::value, std::true_type, std::false_type>::type;
// 32bitまたは64bitの符号なし整数か
template<class T>
using is_unsigned_intle64 = typename std::conditional<is_unsigned_int32<T>::value || is_unsigned_int64<T>::value, std::true_type, std::false_type>::type;

template<class T>
using is_not_t = typename std::conditional<T::value, std::false_type, std::true_type>::type;

unsigned long long random_once(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  static unsigned long long ret = engine();
  return ret;
}

unsigned long long random_number(){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  return engine();
}

// [low, high]
unsigned long long random_number(unsigned long long low, unsigned long long high){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  assert(high >= low);
  unsigned long long diff = high - low + 1;
  return engine() % diff + low;
}
unsigned long long ceillog2(unsigned long long x){
  int res = 1;
  while((1ULL << res) < x) res++;
  return res;
}

// uint32 : uKey ∈ [0, 2^31 - 1)
// uint64 : uKey ∈ [0, 2^63 - 1)
template<typename uKey, typename Val>
struct uhash_map{
  static_assert(is_unsigned_intle64<uKey>::value, "uKey must be unsigned integer (32 or 64bit)");
private:
  using Key = typename std::make_signed<uKey>::type;
  static constexpr int initial_size = 8; // 指定しなかった場合の初期サイズ
  static constexpr float alpha = 0.7; // 占有率がこれを超えると再構築
  static constexpr Key null_val = std::numeric_limits<Key>::min();
  static constexpr Key inf = std::numeric_limits<Key>::max();
  static const unsigned long long r;
  int table_size, table_size_mod;
  int occupied_cnt, elem_cnt; // 使われている要素の数, そのうちまだ消されていない要素の数
  std::vector<std::pair<Key, Val>> v;
  size_t hash(unsigned long long x){
    x += r;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return (x ^ (x >> 31)) & table_size_mod;
  }
  void expand(){
    std::vector<std::pair<Key, Val>> tmp(elem_cnt, {null_val, Val()});
    for(int i = 0, j = 0; i < table_size; i++) if(v[i].first >= 0) tmp[j++] = v[i];
    occupied_cnt = elem_cnt = 0;
    table_size <<= 1;
    table_size_mod = table_size - 1;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
    for(int i = 0; i < tmp.size(); i++) emplace_inner(tmp[i].first, tmp[i].second);
  }
  void emplace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        if(v[i].first == -x - 1){
          elem_cnt++;
          v[i] = {x, y};
        }
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void emplace_replace_inner(Key x, Val y){
    if(occupied_cnt > table_size * alpha) expand();
    int i = hash(x);
    while(true){
      if(v[i].first == null_val){
        v[i] = {x, y};
        occupied_cnt++;
        elem_cnt++;
        return;
      }else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt += (v[i].first == -x - 1);
        v[i] = {x, y};
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  void erase_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return;
      else if(v[i].first == x || v[i].first == -x - 1){
        elem_cnt -= (v[i].first == x);
        v[i].first = -x - 1;
        return;
      }
      i = (i + 1) & table_size_mod;
    }
  }
  bool find_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return false;
      else if(v[i].first == x || v[i].first == -x - 1) return v[i].first == x;
      i = (i + 1) & table_size_mod;
    }
  }
  std::pair<bool, Val> at_inner(Key x){
    int i = hash(x);
    while(true){
      if(v[i].first == null_val) return std::make_pair(false, v[i].second);
      else if(v[i].first == x || v[i].first == -x - 1) return (v[i].first == x ? std::make_pair(true, v[i].second) : std::make_pair(false, v[i].second));
      i = (i + 1) & table_size_mod;
    }
  }
public:
  uhash_map(): table_size(initial_size), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  uhash_map(int _sz): table_size(1 << ceillog2(_sz)), table_size_mod(table_size - 1), occupied_cnt(0), elem_cnt(0), v(table_size, {null_val, Val()}){}
  // 追加, すでにある場合は無視
  void emplace(uKey x, Val y){
    assert(x < inf);
    emplace_inner(x, y);
  }
  // 追加, すでにある場合は置き換える
  void emplace_replace(uKey x, Val y){
    assert(x < inf);
    emplace_replace_inner(x, y);
  }
  // 削除, 無い場合は無視
  void erase(uKey x){
    assert(x < inf);
    erase_inner(x);
  }
  // 検索
  bool find(uKey x){
    assert(x < inf);
    return find_inner(x);
  }
  // 存在するか, 存在する場合その値
  std::pair<bool, Val> at(uKey x){
    assert(x < inf);
    return at_inner(x);
  }
  int size(){
    return elem_cnt;
  }
  bool empty(){
    return elem_cnt == 0;
  }
  std::vector<std::pair<uKey, Val>> enumerate(){
    std::vector<std::pair<uKey, Val>> res;
    for(int i = 0; i < table_size; i++) if(v[i].first >= 0) res.push_back(v[i]);
    return res;
  }
  void clear(){
    table_size = initial_size;
    table_size_mod = table_size - 1;
    occupied_cnt = elem_cnt = 0;
    v = std::vector<std::pair<Key, Val>>(table_size, {null_val, Val()});
  }
};
template<typename uKey, typename Val>
const unsigned long long uhash_map<uKey, Val>::r = random_number();
// 素数m, 数列A, bを与える
// 各a_iに対してb ^ k ≡ a_iを満たすkを返す
template<typename mint>
std::vector<int> bsgs_many(int b, const std::vector<int> &A){
  int init_size = 2e6; // mod998244353, |A| = 2e5で設定 メモリ130MB |A|が大きい場合は1e7などにする 
  init_size = std::min(init_size, mint::mod());
  // 前処理 O(init_size)
  uhash_map<unsigned, int> mp(init_size * 2);
  mint x = 1;
  for(int i = 0; i < init_size; i++){
    mp.emplace(x.val(), i);
    x *= b;
  }
  std::vector<int> res;
  int imax = (mint::mod() + init_size - 1) / init_size;
  mint y = mint(b).pow(2 * mint::mod() - 2 - init_size); // b ^ {-init_size}
  // 計算 O(|A| * mod / init_size)
  for(int a : A){
    x = a;
    for(int i = 0; i < imax; i++){
      auto [f, j] = mp.at(x.val());
      if(f){
        res.push_back(i * init_size + j);
        break;
      }
      x *= y;
    }
  }
  return res;
}
#include <cstdint>

struct barrett_reduction{
  unsigned int mod;
  unsigned long long m;
  barrett_reduction(unsigned int _mod) : mod(_mod){
    m = ((__uint128_t)1 << 64) / mod;
  }
  unsigned int reduce(unsigned int a){
    unsigned long long q = ((__uint128_t)a * m) >> 64;
    a -= q * mod; // 0 <= a < 2 * mod
    // return a;
    return a >= mod ? a - mod : a;
  }
  unsigned int mul(unsigned int a, unsigned int b){
    return reduce((unsigned long long)a * b);
  }
  // {gcd(a, mod), x}, such that a * x ≡ gcd(a, mod)
  std::pair<unsigned int, unsigned int> inv(unsigned int a){
    if(a >= mod) a = reduce(a);
    if(a == 0) return {mod, 0};
    unsigned int s = mod, t = a;
    long long m0 = 0, m1 = 1;
    while(t){
      int u = s / t;
      s -= t * u;
      m0 -= m1 * u;
      std::swap(m0, m1);
      std::swap(s, t);
    }
    if(m0 < 0) m0 += mod / s;
    return {s, m0};
  }
};
// 64bit mod対応
// R = 2^64
// 偶数modだと壊れる
struct montgomery_reduction_64bit{
private:
  // [0, 2 * MOD)
  inline uint64_t reduce_unsafe(__uint128_t x) const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x;
  }
  void _set_mod(uint64_t mod){
    assert((mod < (1ULL << 63)) && (mod & 1));
    MOD = mod;
    NEG_INV = 0;
    __uint128_t s = 1, t = 0;
    for(int i = 0; i < 64; i++){
      if (~t & 1) {
        t += MOD;
        NEG_INV += s;
      }
      t >>= 1;
      s <<= 1;
    }
    R2 = ((__uint128_t)1 << 64) % MOD;
    R2 = R2 * R2 % MOD;
    ONE = generate(1);
  }
  __uint128_t MOD, NEG_INV, R2;
  uint64_t ONE;
public:
  montgomery_reduction_64bit(){}
  montgomery_reduction_64bit(uint64_t mod){_set_mod(mod);}
  void set_mod(uint64_t mod){
    _set_mod(mod);
  }
  uint64_t mod()const{
    return MOD;
  }
  inline uint64_t one()const{
    return ONE;
  }
  inline uint64_t generate(uint64_t x)const{
    return reduce((__uint128_t)x * R2);
  }
  inline uint64_t reduce(__uint128_t x)const{
    x = (x + ((uint64_t)x * (uint64_t)NEG_INV) * MOD) >> 64;
    return x < MOD ? x : x - MOD;
  }
  inline uint64_t fix(uint64_t x)const{
    return x < MOD ? x : x - MOD;
  }
  // [0, 2MOD)
  inline uint64_t mul(uint64_t mx, uint64_t my)const{
    return reduce_unsafe((__uint128_t)mx * my);
  }
  inline uint64_t mul_safe(uint64_t mx, uint64_t my)const{
    return reduce((__uint128_t)mx * my);
  }
  // [0, 2MOD)
  inline uint64_t add(uint64_t mx, uint64_t my)const{
    return (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
  }
  inline uint64_t add_safe(uint64_t mx, uint64_t my)const{
    uint64_t res = (mx >= MOD ? mx - MOD : mx) + (my >= MOD ? my - MOD : my);
    return res >= MOD ? res - MOD : res;
  }
  // [0, 2MOD)
  inline uint64_t sub(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    return mx >= my ? mx - my : mx + MOD - my;
  }
  inline uint64_t sub_safe(uint64_t mx, uint64_t my)const{
    if(my >= MOD) my -= MOD;
    uint64_t res = mx >= my ? mx - my : mx + MOD - my;
    return res >= MOD ? res - MOD : res;
  }
  inline uint64_t pow(uint64_t ma, uint64_t b)const{
    uint64_t ret = one();
    while(b){
      if(b & 1) ret = mul(ret, ma);
      ma = mul(ma, ma);
      b >>= 1;
    }
    return ret;
  }
  inline uint64_t pow_safe(uint64_t ma, uint64_t b)const{
    return fix(pow(ma, b));
  }
};
unsigned long long mod_pow_mr(unsigned long long a, unsigned long long b, unsigned long long m){
  montgomery_reduction_64bit mr(m);
  return mr.reduce(mr.pow(mr.generate(a), b));
}
bool _miller_rabin_mr(unsigned long long n, const montgomery_reduction_64bit &mr){
  static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
  static std::vector<unsigned long long> A{2, 325, 9375, 28178, 450775, 9780504, 1795265022};
  static std::vector<unsigned long long> B{2, 7, 61};
  if(n <= 1) return false;
  if(n <= 50){
    for(int l = n < 20 ? 0 : 8, r = n < 20 ? 8 : 15; l < r; l++) if(small_p[l] == n) return true;
    return false;
  }
  if(!(n & 1)) return false;
  unsigned long long d = n - 1;
  unsigned long long one = mr.one(), mone = mr.generate(n - 1);
  d >>= __builtin_ctzll(d);
  for(unsigned long long a : (n >> 32) ? A : B){
    if(a % n == 0) continue;
    unsigned long long d2s = d; // d * 2^s, 0 <= s <= (n - 1)が2で割れる回数
    unsigned long long y = mr.pow_safe(mr.generate(a), d);
    while(d2s != n - 1 && y != one && y != mone){
      y = mr.mul_safe(y, y);
      d2s <<= 1;
    }
    if(y != mone && !(d2s & 1)) return false;
  }
  return true;
}
bool miller_rabin_mr(unsigned long long n){
  if(n % 2 == 0) return n == 2 ? true : false;
  montgomery_reduction_64bit mr(n);
  return _miller_rabin_mr(n, mr);
}
// https://en.wikipedia.org/wiki/Binary_GCD_algorithm
unsigned long long binary_gcd(unsigned long long a, unsigned long long b){
  if(!a || !b) return !a ? b : a;
  int shift = __builtin_ctzll(a | b); // [1] gcd(2a', 2b') = 2 * gcd(a', b')
  a >>= __builtin_ctzll(a);
  do{
    // if b is odd
    // gcd(2a', b) = gcd(a', b), if a = 2a'(a is even)
    // gcd(a, b) = gcd(|a - b|, min(a, b)), if a is odd
    b >>= __builtin_ctzll(b); // make b odd
    if(a > b) std::swap(a, b);
    b -= a;
  }while(b); // gcd(a, 0) = a
  return a << shift; // [1]
}
unsigned long long generate_random_prime(unsigned long long min_n = 2, unsigned long long max_n = ~0ULL){
  std::random_device seed_gen;
  std::mt19937_64 engine(seed_gen());
  __uint128_t len = max_n - min_n + 1;
  // https://en.wikipedia.org/wiki/Prime_number_theorem
  while(true){
    unsigned long long a = engine() % len + min_n;
    if(miller_rabin_mr(a)){
      return a;
    }
  }
}
namespace rho_factorization{
  unsigned long long rho(unsigned long long n){
    static std::vector<int> small_p{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};

    for(int sp : small_p) if(n % sp == 0) return sp; // n < 50

    montgomery_reduction_64bit mr(n);
    if(_miller_rabin_mr(n, mr)) return n;

    auto try_factorize = [n, mr](unsigned long long c){
      c = mr.generate(c);
      auto f = [mr, c](unsigned long long mx){
        return mr.add(mr.mul(mx, mx), c);
      };
      unsigned long long m = 1LL << ((64 - __builtin_clzll(n)) / 8);
      unsigned long long y = n, r = 1, q = 1;
      unsigned long long x, g, k, ys;
      do{
        x = y;
        y = mr.generate(y);
        for(int i = 0; i < r; i++) y = f(y);
        y = mr.reduce(y);

        k = 0;
        while(k < r && g == 1){
          q = mr.generate(q);
          y = mr.generate(y);
          ys = y;
          for(int i = 0; i < std::min(m, r - k); i++){
            y = f(y);
            unsigned long long z = mr.reduce(y);
            q = mr.mul(q, mr.generate(x > z ? x - z : z - x));
          }
          y = mr.reduce(y);
          g = binary_gcd(mr.reduce(q), n);
          k += m;
        }
        r <<= 1;
      }while(g == 1);
      if(g == n){
        do{
          ys = f(ys);
          unsigned long long z = mr.reduce(ys);
          g = binary_gcd(x > z ? x - z : z - x, n);
        }while(g == 1);
      }
      return g; // g == n when failure
    };
    unsigned long long c = 1, res = n;
    do{
      res = try_factorize(c);
      // c = generate_random_prime(2, n - 1);
      c = (c + 1) % n;
    }while(res == n);
    return res;
  }
  std::vector<unsigned long long> factorize(unsigned long long n){
    if(n <= 1) return {};
    unsigned long long x = rho(n);
    if(x == n) return {x};
    auto l = factorize(x);
    auto r = factorize(n / x);
    l.insert(l.end(), r.begin(), r.end());
    return l;
  }
  // {素数, 個数}の形で返す
  std::vector<std::pair<unsigned long long, int>> factorize2(unsigned long long n){
    auto p = factorize(n);
    sort(p.begin(), p.end());
    std::vector<std::pair<unsigned long long, int>> ret;
    for(int i : p){
      if(ret.empty() || ret.back().first != i) ret.push_back({i, 1});
      else ret.back().second++;
    }
    return ret;
  }
  // 素因数の集合(重複なし, ソート済)を返す
  std::vector<unsigned long long> prime_factor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());
    p.erase(std::unique(p.begin(), p.end()), p.end());
    return p;
  }
  // 10^18以下の高度合成数 897612484786617600の約数が103680個なので全列挙して良さそう
  std::vector<unsigned long long> divisor(unsigned long long n){
    auto p = factorize(n);
    std::sort(p.begin(), p.end());

    std::vector<std::pair<unsigned long long, int>> x;

    for(int i = 0; i < p.size(); i++){
      if(!i || p[i] != p[i - 1]) x.push_back({p[i], 1});
      else x.back().second++;
    }
    int sz = 1;
    for(auto [p_cur, cnt] : x) sz *= cnt + 1;

    std::vector<unsigned long long> res(sz);
    res[0] = 1;
    int r_prev = 1, r = 1;
    for(auto [p_cur, cnt] : x){
      unsigned long long ppow = 1;
      for(int c = 0; c < cnt; c++){
        ppow *= p_cur;
        for(int i = 0; i < r_prev; i++){
          res[r++] = res[i] * ppow;
        }
      }
      r_prev = r;
    }
    return res;
  }
  int mobius_function(long long x){
    auto P = rho_factorization::factorize(x);
    for(long long p : P) if((x / p) % p == 0) return 0;
    return P.size() % 2 == 0 ? 1 : -1;
  }
  unsigned long long totient_function(unsigned long long n){
    unsigned long long res = n;
    auto prims = rho_factorization::prime_factor(n);
    for(auto p : prims) res -= res / p;
    return res;
  }
};
// p: 素数
unsigned long long find_primitive_root(unsigned long long p){
  static std::random_device seed_gen;
  static std::mt19937_64 engine(seed_gen());
  //assert(miller_rabin_mr(p));
  auto primes = rho_factorization::prime_factor(p - 1);
  while(true){
    bool f = true;
    unsigned long long a = engine() % (p - 1) + 1;
    for(unsigned long long pk : primes){
      // a ^ (p - 1) / pk ≡ 1 (mod p) -> no
      if(mod_pow_mr(a, (p - 1) / pk, p) == 1){
        f = false;
        break;
      }
    }
    if(f) return a;
  }
}
using mint = dynamic_modint<0>;

int main(){
  int p, t;
  std::cin >> p >> t;
  mint::set_mod(p);
  int kon = find_primitive_root(p);
  vector<int> N, G, X;
  range(i, 0, t){
    int n;
    std::cin >> n;
    N.push_back(n);
    range(j, 0, n){
      int g;
      std::cin >> g;
      G.push_back(g);
    }
    int x;
    std::cin >> x;
    X.push_back(x);
  }
  range(i, 0, t) G.push_back(X[i]);

  accumulate1d<int> Nac(N);
  auto b = bsgs_many<mint>(kon, G);
  int q = p - 1;
  range(i, 0, t){
    int lid = Nac.query(0, i);
    int rid = lid + N[i];
    int g_ = q;
    range(j, lid, rid) g_ = gcd(g_, b[j]);
    int d = b[Nac.query(0, t) + i];
    if(d % g_ == 0){
      std::cout << 1 << '\n';
    }else{
      std::cout << 0 << '\n';
    }
  }
}
accuracy: 0.029411764705882353
time_ms: 80
memory_kb: 35848
final_rank: 20

code_snippet: //
// calc order
//   min: x s.t. a^x \equiv 1 (mod p)
//
// verified:
//   AtCoder ABC 335 G - Discrete Logarithm Problems
//     https://atcoder.jp/contests/abc335/tasks/abc335_g
//
//   AOJ 3062 Product
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3062
//


#include <bits/stdc++.h>
using namespace std;


// mod_pow, mod_inv
template<class T> T mod_pow(T a, T n, T m) {
    T res = 1;
    while (n > 0) {
        if (n % 2 == 1) res = res * a % m;
        a = a * a % m;
        n >>= 1;
    }
    return res;
};

template<class T> T mod_inv(T a, T m) {
    T b = m, u = 1, v = 0;
    while (b > 0) {
        T t = a / b;
        a -= t * b, swap(a, b);
        u -= t * v, swap(u, v);
    }
    u %= m;
    if (u < 0) u += m;
    return u;
};

// montgomery modint (MOD < 2^62, MOD is odd)
struct MontgomeryModInt64 {
    using mint = MontgomeryModInt64;
    using u64 = uint64_t;
    using u128 = __uint128_t;
    
    // static menber
    static u64 MOD;
    static u64 INV_MOD;  // INV_MOD * MOD ≡ 1 (mod 2^64)
    static u64 T128;  // 2^128 (mod MOD)
    
    // inner value
    u64 val;
    
    // constructor
    MontgomeryModInt64() : val(0) { }
    MontgomeryModInt64(long long v) : val(reduce((u128(v) + MOD) * T128)) { }
    u64 get() const {
        u64 res = reduce(val);
        return res >= MOD ? res - MOD : res;
    }
    
    // mod getter and setter
    static u64 get_mod() { return MOD; }
    static void set_mod(u64 mod) {
        assert(mod < (1LL << 62));
        assert((mod & 1));
        MOD = mod;
        T128 = -u128(mod) % mod;
        INV_MOD = get_inv_mod();
    }
    static u64 get_inv_mod() {
        u64 res = MOD;
        for (int i = 0; i < 5; ++i) res *= 2 - MOD * res;
        return res;
    }
    static u64 reduce(const u128 &v) {
        return (v + u128(u64(v) * u64(-INV_MOD)) * MOD) >> 64;
    }
    
    // arithmetic operators
    mint operator + () const { return mint(*this); }
    mint operator - () const { return mint() - mint(*this); }
    mint operator + (const mint &r) const { return mint(*this) += r; }
    mint operator - (const mint &r) const { return mint(*this) -= r; }
    mint operator * (const mint &r) const { return mint(*this) *= r; }
    mint operator / (const mint &r) const { return mint(*this) /= r; }
    mint& operator += (const mint &r) {
        if ((val += r.val) >= 2 * MOD) val -= 2 * MOD;
        return *this;
    }
    mint& operator -= (const mint &r) {
        if ((val += 2 * MOD - r.val) >= 2 * MOD) val -= 2 * MOD;
        return *this;
    }
    mint& operator *= (const mint &r) {
        val = reduce(u128(val) * r.val);
        return *this;
    }
    mint& operator /= (const mint &r) {
        *this *= r.inv();
        return *this;
    }
    mint inv() const { return pow(MOD - 2); }
    mint pow(u128 n) const {
        mint res(1), mul(*this);
        while (n > 0) {
            if (n & 1) res *= mul;
            mul *= mul;
            n >>= 1;
        }
        return res;
    }

    // other operators
    bool operator == (const mint &r) const {
        return (val >= MOD ? val - MOD : val) == (r.val >= MOD ? r.val - MOD : r.val);
    }
    bool operator != (const mint &r) const {
        return (val >= MOD ? val - MOD : val) != (r.val >= MOD ? r.val - MOD : r.val);
    }
    mint& operator ++ () {
        ++val;
        if (val >= MOD) val -= MOD;
        return *this;
    }
    mint& operator -- () {
        if (val == 0) val += MOD;
        --val;
        return *this;
    }
    mint operator ++ (int) {
        mint res = *this;
        ++*this;
        return res;
    }
    mint operator -- (int) {
        mint res = *this;
        --*this;
        return res;
    }
    friend istream& operator >> (istream &is, mint &x) {
        long long t;
        is >> t;
        x = mint(t);
        return is;
    }
    friend ostream& operator << (ostream &os, const mint &x) {
        return os << x.get();
    }
    friend mint pow(const mint &r, long long n) {
        return r.pow(n);
    }
    friend mint inv(const mint &r) {
        return r.inv();
    }
};

typename MontgomeryModInt64::u64
MontgomeryModInt64::MOD, MontgomeryModInt64::INV_MOD, MontgomeryModInt64::T128;


// Miller-Rabin
bool MillerRabin(long long N, const vector<long long> &A) {
    assert(N % 2 == 1);
    assert(N < (1LL<<62));
    using mint = MontgomeryModInt64;
    mint::set_mod(N);
    
    long long s = 0, d = N - 1;
    while (d % 2 == 0) {
        ++s;
        d >>= 1;
    }
    for (auto a : A) {
        if (N <= a) return true;
        mint x = mint(a).pow(d);
        if (x != 1) {
            long long t;
            for (t = 0; t < s; ++t) {
                if (x == N - 1) break;
                x *= x;
            }
            if (t == s) return false;
        }
    }
    return true;
}

bool is_prime(long long N) {
    if (N <= 1) return false;
    else if (N == 2) return true;
    else if (N % 2 == 0) return false;
    else if (N < 4759123141LL)
        return MillerRabin(N, {2, 7, 61});
    else
        return MillerRabin(N, {2, 325, 9375, 28178, 450775, 9780504, 1795265022});
}


// Pollard's Rho
unsigned int xor_shift_rng() {
    static unsigned int tx = 123456789, ty=362436069, tz=521288629, tw=88675123;
    unsigned int tt = (tx^(tx<<11));
    tx = ty, ty = tz, tz = tw;
    return ( tw=(tw^(tw>>19))^(tt^(tt>>8)) );
}

long long pollard(long long N) {
    if (N % 2 == 0) return 2;
    if (is_prime(N)) return N;
    
    assert(N < (1LL<<62));
    using mint = MontgomeryModInt64;
    mint::set_mod(N);
    
    long long step = 0;
    while (true) {
        mint r = xor_shift_rng();  // random r
        auto f = [&](mint x) -> mint { return x * x + r; };
        mint x = ++step, y = f(x);
        while (true) {
            long long p = gcd((y - x).get(), N);
            if (p == 0 || p == N) break;
            if (p != 1) return p;
            x = f(x);
            y = f(f(y));
        }
    }
}

vector<long long> pollard_prime_factorize(long long N) {
    if (N == 1) return {};
    long long p = pollard(N);
    if (p == N) return {p};
    vector<long long> left = pollard_prime_factorize(p);
    vector<long long> right = pollard_prime_factorize(N / p);
    if (left.size() > right.size()) swap(left, right);
    left.insert(left.end(), right.begin(), right.end());
    sort(left.begin(), left.end());
    return left;
}

vector<pair<long long, long long>> prime_factorize(long long N) {
    vector<pair<long long, long long>> res;
    const auto &prs = pollard_prime_factorize(N);
    long long prev = -1, num = 0;
    for (const auto &pr : prs) {
        if (pr == prev) ++num;
        else {
            if (prev != -1) res.emplace_back(prev, num);
            prev = pr, num = 1;
        }
    }
    if (prev != -1) res.emplace_back(prev, num);
    return res;
}


// various methods mod prime P
struct PrimeProcessor {
    using mint = MontgomeryModInt64;
    
    // input prime
    long long prime;
    vector<pair<long long, long long>> pf;  // prime factorization of p-1
    
    // constructors
    PrimeProcessor() {}
    PrimeProcessor(long long p) : prime(p) {
        init(p);
    }
    
    // initializer
    void init(long long p) {
        assert(is_prime(p));
        prime = p;
        if (p % 2 == 1) {
            assert(p < (1LL<<62));
            prime = p;
            pf = prime_factorize(prime - 1);
            mint::set_mod(prime);
        }
    }
    
    // min: x s.t. a^x \equiv 1 (mod prime)
    long long calc_order(long long a) {
        assert(a != 0);
        if (prime == 2) return 1;
        long long res = prime - 1;
        for (const auto &[p, num] : pf) {
            while (res % p == 0 && mint(a).pow(res / p) == 1) res /= p;
        }
        return res;
    }
};



/*/////////////////////////////*/
// Examples
/*/////////////////////////////*/

void ABC_335_G() {
    long long N, P;
    cin >> N >> P;
    vector<long long> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    PrimeProcessor pp(P);
    map<long long, long long> ma;
    for (auto a : A) {
        long long order = pp.calc_order(a);
        ++ma[order];
    }

    long long res = 0;
    for (auto [v1, num1] : ma) {
        for (auto [v2, num2] : ma) {
            if (v2 % v1 == 0) res += num1 * num2;
        }
    }
    cout << res << endl;
}

void AOJ_3062() {
    int P, T;
    cin >> P >> T;
    PrimeProcessor pp(P);
    while (T--) {
        int N, A;
        cin >> N;
        int g = P - 1;
        for (int i = 0; i < N; ++i) {
            int G;
            cin >> G;
            g = gcd(g, (P - 1) / pp.calc_order(G));
        }
        cin >> A;
        int ga = (P - 1) / pp.calc_order(A);
        cout << (ga % g ? 0 : 1) << endl;
    }
}


int main() {
    //ABC_335_G();
    AOJ_3062();
}
accuracy: 1
time_ms: 270
memory_kb: 3488
final_rank: 1

code_snippet: using namespace std;
#include<bits/stdc++.h>
void _main();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(30);_main();return 0;}
typedef long long ll;typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef string str;
#define rep1(a)          for(ll i = 0; i < (a); i++)
#define rep2(i, a)       for(ll i = 0; i < (a); i++)
#define rep3(i, a, b)    for(ll i = (a); i < (b); i++)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define ALL(x) std::begin(x),std::end(x)
#define rALL(x) std::rbegin(x),std::rend(x)
#define INF ((1LL<<62)-(1LL<<31))
#define bit(x,i) (((x)>>(i))&1)
#define fi first
#define se second
#define pb push_back
#define Endl endl
#define spa " "
#define YesNo(x) cout<<(x?"Yes":"No")<<endl;
#define eps (1e-10)

//コンパイル時の引数にBLUEBERRYを渡すとdeb関数が使える
#ifdef BLUEBERRY
#define deb print
// #define _GLIBCXX_DEBUG
#else
#define deb(...)
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
//！？！？
#define O print
//可変長引数で入力を受け取りつつ変数を宣言
inline void scan(){}
template<class Head,class... Tail>
inline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
//vectorのcin
template<typename T>
std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
//vectorのcout
template<typename T>
std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
//x,y,x,yを渡すとldで距離を返す
long double my_distance(long double xi,long double yi,long double xj,long double yj){return sqrt(abs((xi-xj)*(xi-xj))+abs((yi-yj)*(yi-yj)));}
//可変長引数のprint関数
void print(){cout << '\n';}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
//可変長引数のmin
template<class... T>
constexpr auto min(T... a){return min(initializer_list<common_type_t<T...>>{a...});}
//可変長引数のmax
template<class... T>
constexpr auto max(T... a){return max(initializer_list<common_type_t<T...>>{a...});}
template<typename T,typename U>inline bool chmax(T&a,U b){if(a<b){a=b;return 1;}return 0;}
template<typename T,typename U>inline bool chmin(T&a,U b){if(a>b){a=b;return 1;}return 0;}
template<typename T> inline T sum(vector<T>&a){T ret{};for(auto&i:a)ret+=i;return ret;}
template<typename T> inline T min(vector<T>&a){T ret=a[0];for(auto&i:a)chmin(ret,i);return ret;}
template<typename T> inline T max(vector<T>&a){T ret=a[0];for(auto&i:a)chmax(ret,i);return ret;}
template<typename T> inline int len(vector<T>&a){return a.size();}
inline int len(string&a){return a.size();}
// n次元配列の初期化。第２引数の型のサイズごとに初期化していく。
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){std::fill( (T*)array, (T*)(array+N), val );}
//こめんとを付け外ししてMODを切り替える
//ll MOD = INF;
// ll MOD = 1000000007;
ll MOD = 998244353;

//from:https://kenkoooo.hatenablog.com/entry/2016/11/30/163533 int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {std::ostream::sentry s(dest);if (s){__uint128_t tmp = value < 0 ? -value : value;char buffer[128];char *d = std::end(buffer);do{--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest;}
__int128 parsetoint128(string &s) {__int128 ret = 0;for (int i = 0; i < (int)s.length(); i++)if ('0' <= s[i] && s[i] <= '9')ret=10*ret+(__int128_t)(s[i]-'0');return ret;}

//回文判定 
bool iskaibun(string s){ll k = s.size();rep(i,0,k/2){if(s[i]!=s[k-1-i]){return false;}}return true;}

//二部グラフ判定 重みなしグラフを引数に取り、boolを返す
bool isbipartite_graph(vector<vector<ll>>&g){ll v = g.size();vector<ll>col(v,-1);vector<bool>used(v,false);bool ret = true;rep(i,v){if(used[i])continue;col[i]=0;[DFS([&](auto&&f,ll pos,ll pr)->void{if(used[pos])return;used[pos]=true;for(auto to:g[pos]){if(to==pr)continue;if(used[to]&&col[pos]==col[to]){ret = false;return;}if(used[to])continue;col[to]=col[pos]^1;f(f,to,pos);}}),&i]{DFS(DFS,i,-1);}();}return ret;}
//a~bの和 a<b
ll ran(ll a,ll b){return ((a+b)*(b-a+1))/2;}
//座圧する
ll zaatu(vector<ll>&A){map<ll,ll>m;for(auto&&x:A)m[x]=0;ll ret = 0;for(auto&&[key,val]:m)val=ret++;for(auto&&x:A)x=m[x];return ret;}
//約数列挙　引数に取った整数の約数のvectorを返す
vector<ll>enumdiv(ll n){vector<ll>s;for(ll i = 1;i*i<=n;i++){if(n%i==0){s.push_back(i);if(i*i!=n)s.push_back(n/i);}}return s;}
//トポロジカルソート グラフ、入次数カウント、頂点数を引数で渡すと、トポロジカルソートされた頂点列を返す
vector<ll> topo_sort(vector<vector<ll>>&G,vector<ll>&nyu_cnt,ll v){vector<ll>ret;priority_queue<ll,vector<ll>,greater<ll>>pq;rep(i,0,v){if(nyu_cnt[i]==0)pq.push(i);}while(!pq.empty()){ll pos = pq.top();pq.pop();for(ll i:G[pos]){nyu_cnt[i]--;if(nyu_cnt[i]==0)pq.push(i);}ret.push_back(pos);}return ret;}
//素因数分解 pair<素数、指数>のvectorを返す
vector<pair<ll,ll>> soinsu_bunkai(ll x){vector<pair<ll,ll>>ret;rep(i,2,sqrt(x)+1){if(x%i==0){ll cnt{};while(x%i==0){x/=i;cnt++;}ret.push_back({i,cnt});}}if(x!=1)ret.push_back({x,1});return ret;}
//二項係数MOD MODは上の方で設定、MAXまでのnCrをCOM(n,r)でとれる
const int MAX = 5000010;
ll fac[MAX], finv[MAX], invv[MAX];
void COMinit(){fac[0]=fac[1]=finv[0]=finv[1]=invv[1]=1;for(int i=2;i<MAX;i++){fac[i]=fac[i-1]*i%MOD;invv[i]=MOD-invv[MOD%i]*(MOD/i)%MOD;finv[i]=finv[i-1]*invv[i]%MOD;}}
ll COM(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;}
ll nPr(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[n-k]);}
//エラトステネスの篩　isprimeには素数かどうかが入っている
vector<bool> isprime;vector<int> Era(int n) {isprime.resize(n, true);vector<int> res;isprime[0] = false; isprime[1] = false;for (int i = 2; i < n; ++i) isprime[i] = true;for (int i = 2; i < n; ++i){if (isprime[i]) {res.push_back(i);for (int j = i*2; j < n; j += i) isprime[j] = false;}}return res;}
//Union-Find from https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/vi((b%2==0?b-1:b)+2-(a%2==0?a+1:a))/2er/union-find
class UnionFind{public:UnionFind()=default;explicit UnionFind(size_t n):m_parentsOrSize(n, -1){}int find(int i){if(m_parentsOrSize[i]<0){return i;}return(m_parentsOrSize[i]=find(m_parentsOrSize[i]));}void merge(int a,int b){a=find(a);b=find(b);if(a!=b){if(-m_parentsOrSize[a]<-m_parentsOrSize[b]){std::swap(a,b);}m_parentsOrSize[a]+=m_parentsOrSize[b];m_parentsOrSize[b]=a;}}bool connected(int a,int b){return (find(a)==find(b));}int size(int i){return -m_parentsOrSize[find(i)];}private:std::vector<int>m_parentsOrSize;};
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
ll dx[8] = {0,1,0,-1,-1,-1,1,1},dy[8]={1,0,-1,0,-1,1,-1,1};

ll p;
vector<pair<ll,ll>>soi;
bool solve();
void _main(){
[]{[]{[]{[]{[]{}();}();}();}();}();
	cin >> p;
	soi = soinsu_bunkai(p-1);
	int testcase = 1;
	cin >> testcase;
	for(;testcase--;){
		if(solve()){
			O(1);
			// O("Yes");
		}
		else{
			O(0);
			// O("-1");
			// O("No");
		}
	}
	cout<<flush;
[]{[]{[]{[]{[]{}();}();}();}();}();
}

// #include<atcoder/all>
// using namespace atcoder;
// using mint = modint998244353;
// using mint1 = modint1000000007;
__int128_t modpow(__int128_t x,__int128_t y){
	__int128_t now = x;
	__int128_t ret = 1;
	while(y>0){
		if(y&1){
			ret *= now;
			ret %= p;
		}
		now *= now;
		now %= p;
		y >>= 1ull;
	}
	return ret;
}
bool solve(){
	LL(n);
	vector<ll>a(n);cin >> a;
	sort(ALL(a));
	LL(A);
	//Aの位数を求める。
	ll Ai = p-1;
	for(auto[num,val]:soi){
		while(Ai%num==0&&modpow(A,Ai/num)==1)Ai/=num;
	}
	ll ans = p-1;
	rep(i,n){
		ll m = p-1;
		for(auto[num,val]:soi){
			while(m%num==0&&modpow(a[i],m/num)==1)m/=num;
		}
		ans = gcd(ans,(p-1)/m);
	}
	if(((p-1)/Ai)%ans==0)return 1;
	return 0;
}
accuracy: 1
time_ms: 620
memory_kb: 3884
final_rank: 4

code_snippet: using namespace std;
#include<bits/stdc++.h>
void _main();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(30);_main();return 0;}
typedef long long ll;typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef string str;
#define rep1(a)          for(ll i = 0; i < (a); i++)
#define rep2(i, a)       for(ll i = 0; i < (a); i++)
#define rep3(i, a, b)    for(ll i = (a); i < (b); i++)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define ALL(x) std::begin(x),std::end(x)
#define rALL(x) std::rbegin(x),std::rend(x)
#define INF ((1LL<<62)-(1LL<<31))
#define bit(x,i) (((x)>>(i))&1)
#define fi first
#define se second
#define pb push_back
#define Endl endl
#define spa " "
#define YesNo(x) cout<<(x?"Yes":"No")<<endl;
#define eps (1e-10)

//コンパイル時の引数にBLUEBERRYを渡すとdeb関数が使える
#ifdef BLUEBERRY
#define deb print
// #define _GLIBCXX_DEBUG
#else
#define deb(...)
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
//！？！？
#define O print
//可変長引数で入力を受け取りつつ変数を宣言
inline void scan(){}
template<class Head,class... Tail>
inline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
//vectorのcin
template<typename T>
std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
//vectorのcout
template<typename T>
std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
//x,y,x,yを渡すとldで距離を返す
long double my_distance(long double xi,long double yi,long double xj,long double yj){return sqrt(abs((xi-xj)*(xi-xj))+abs((yi-yj)*(yi-yj)));}
//可変長引数のprint関数
void print(){cout << '\n';}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
//可変長引数のmin
template<class... T>
constexpr auto min(T... a){return min(initializer_list<common_type_t<T...>>{a...});}
//可変長引数のmax
template<class... T>
constexpr auto max(T... a){return max(initializer_list<common_type_t<T...>>{a...});}
template<typename T,typename U>inline bool chmax(T&a,U b){if(a<b){a=b;return 1;}return 0;}
template<typename T,typename U>inline bool chmin(T&a,U b){if(a>b){a=b;return 1;}return 0;}
template<typename T> inline T sum(vector<T>&a){T ret{};for(auto&i:a)ret+=i;return ret;}
template<typename T> inline T min(vector<T>&a){T ret=a[0];for(auto&i:a)chmin(ret,i);return ret;}
template<typename T> inline T max(vector<T>&a){T ret=a[0];for(auto&i:a)chmax(ret,i);return ret;}
template<typename T> inline int len(vector<T>&a){return a.size();}
inline int len(string&a){return a.size();}
// n次元配列の初期化。第２引数の型のサイズごとに初期化していく。
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){std::fill( (T*)array, (T*)(array+N), val );}
//こめんとを付け外ししてMODを切り替える
//ll MOD = INF;
// ll MOD = 1000000007;
ll MOD = 998244353;

//from:https://kenkoooo.hatenablog.com/entry/2016/11/30/163533 int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {std::ostream::sentry s(dest);if (s){__uint128_t tmp = value < 0 ? -value : value;char buffer[128];char *d = std::end(buffer);do{--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest;}
__int128 parsetoint128(string &s) {__int128 ret = 0;for (int i = 0; i < (int)s.length(); i++)if ('0' <= s[i] && s[i] <= '9')ret=10*ret+(__int128_t)(s[i]-'0');return ret;}

//回文判定 
bool iskaibun(string s){ll k = s.size();rep(i,0,k/2){if(s[i]!=s[k-1-i]){return false;}}return true;}

//二部グラフ判定 重みなしグラフを引数に取り、boolを返す
bool isbipartite_graph(vector<vector<ll>>&g){ll v = g.size();vector<ll>col(v,-1);vector<bool>used(v,false);bool ret = true;rep(i,v){if(used[i])continue;col[i]=0;[DFS([&](auto&&f,ll pos,ll pr)->void{if(used[pos])return;used[pos]=true;for(auto to:g[pos]){if(to==pr)continue;if(used[to]&&col[pos]==col[to]){ret = false;return;}if(used[to])continue;col[to]=col[pos]^1;f(f,to,pos);}}),&i]{DFS(DFS,i,-1);}();}return ret;}
//a~bの和 a<b
ll ran(ll a,ll b){return ((a+b)*(b-a+1))/2;}
//座圧する
ll zaatu(vector<ll>&A){map<ll,ll>m;for(auto&&x:A)m[x]=0;ll ret = 0;for(auto&&[key,val]:m)val=ret++;for(auto&&x:A)x=m[x];return ret;}
//約数列挙　引数に取った整数の約数のvectorを返す
vector<ll>enumdiv(ll n){vector<ll>s;for(ll i = 1;i*i<=n;i++){if(n%i==0){s.push_back(i);if(i*i!=n)s.push_back(n/i);}}return s;}
//トポロジカルソート グラフ、入次数カウント、頂点数を引数で渡すと、トポロジカルソートされた頂点列を返す
vector<ll> topo_sort(vector<vector<ll>>&G,vector<ll>&nyu_cnt,ll v){vector<ll>ret;priority_queue<ll,vector<ll>,greater<ll>>pq;rep(i,0,v){if(nyu_cnt[i]==0)pq.push(i);}while(!pq.empty()){ll pos = pq.top();pq.pop();for(ll i:G[pos]){nyu_cnt[i]--;if(nyu_cnt[i]==0)pq.push(i);}ret.push_back(pos);}return ret;}
//素因数分解 pair<素数、指数>のvectorを返す
vector<pair<ll,ll>> soinsu_bunkai(ll x){vector<pair<ll,ll>>ret;rep(i,2,sqrt(x)+1){if(x%i==0){ll cnt{};while(x%i==0){x/=i;cnt++;}ret.push_back({i,cnt});}}if(x!=1)ret.push_back({x,1});return ret;}
//二項係数MOD MODは上の方で設定、MAXまでのnCrをCOM(n,r)でとれる
const int MAX = 5000010;
ll fac[MAX], finv[MAX], invv[MAX];
void COMinit(){fac[0]=fac[1]=finv[0]=finv[1]=invv[1]=1;for(int i=2;i<MAX;i++){fac[i]=fac[i-1]*i%MOD;invv[i]=MOD-invv[MOD%i]*(MOD/i)%MOD;finv[i]=finv[i-1]*invv[i]%MOD;}}
ll COM(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;}
ll nPr(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[n-k]);}
//エラトステネスの篩　isprimeには素数かどうかが入っている
vector<bool> isprime;vector<int> Era(int n) {isprime.resize(n, true);vector<int> res;isprime[0] = false; isprime[1] = false;for (int i = 2; i < n; ++i) isprime[i] = true;for (int i = 2; i < n; ++i){if (isprime[i]) {res.push_back(i);for (int j = i*2; j < n; j += i) isprime[j] = false;}}return res;}
//Union-Find from https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/vi((b%2==0?b-1:b)+2-(a%2==0?a+1:a))/2er/union-find
class UnionFind{public:UnionFind()=default;explicit UnionFind(size_t n):m_parentsOrSize(n, -1){}int find(int i){if(m_parentsOrSize[i]<0){return i;}return(m_parentsOrSize[i]=find(m_parentsOrSize[i]));}void merge(int a,int b){a=find(a);b=find(b);if(a!=b){if(-m_parentsOrSize[a]<-m_parentsOrSize[b]){std::swap(a,b);}m_parentsOrSize[a]+=m_parentsOrSize[b];m_parentsOrSize[b]=a;}}bool connected(int a,int b){return (find(a)==find(b));}int size(int i){return -m_parentsOrSize[find(i)];}private:std::vector<int>m_parentsOrSize;};
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
ll dx[8] = {0,1,0,-1,-1,-1,1,1},dy[8]={1,0,-1,0,-1,1,-1,1};

ll p;
vector<pair<ll,ll>>soi;
bool solve();
void _main(){
[]{[]{[]{[]{[]{}();}();}();}();}();
	cin >> p;
	soi = soinsu_bunkai(p-1);
	int testcase = 1;
	cin >> testcase;
	for(;testcase--;){
		if(solve()){
			O(1);
			// O("Yes");
		}
		else{
			O(0);
			// O("-1");
			// O("No");
		}
	}
	cout<<flush;
[]{[]{[]{[]{[]{}();}();}();}();}();
}

// #include<atcoder/all>
// using namespace atcoder;
// using mint = modint998244353;
// using mint1 = modint1000000007;
__int128_t modpow(__int128_t x,__int128_t y){
	__int128_t now = x;
	__int128_t ret = 1;
	while(y>0){
		if(y&1){
			ret *= now;
			ret %= p;
		}
		now *= now;
		now %= p;
		y >>= 1ull;
	}
	return ret;
}
bool solve(){
	LL(n);
	vector<ll>a(n);cin >> a;
	sort(ALL(a));
	LL(A);
	//Aの位数を求める。
	ll Ai = p-1;
	for(auto[num,val]:soi){
		while(Ai%num==0&&modpow(A,Ai/num)==1)Ai/=num;
	}
	rep(i,n){
		ll m = p-1;
		for(auto[num,val]:soi){
			while(m%num==0&&modpow(a[i],m/num)==1)m/=num;
		}
		deb(i,m,Ai,A,a[i]);
		if(m%Ai==0)return 1;
		if(Ai%m==0)Ai/=m;
	}
	return 0;
}
accuracy: 0.058823529411764705
time_ms: 470
memory_kb: 3408
final_rank: 16

code_snippet: using namespace std;
#include<bits/stdc++.h>
void _main();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(30);_main();return 0;}
typedef long long ll;typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef string str;
#define rep1(a)          for(ll i = 0; i < (a); i++)
#define rep2(i, a)       for(ll i = 0; i < (a); i++)
#define rep3(i, a, b)    for(ll i = (a); i < (b); i++)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define ALL(x) std::begin(x),std::end(x)
#define rALL(x) std::rbegin(x),std::rend(x)
#define INF ((1LL<<62)-(1LL<<31))
#define bit(x,i) (((x)>>(i))&1)
#define fi first
#define se second
#define pb push_back
#define Endl endl
#define spa " "
#define YesNo(x) cout<<(x?"Yes":"No")<<endl;
#define eps (1e-10)

//コンパイル時の引数にBLUEBERRYを渡すとdeb関数が使える
#ifdef BLUEBERRY
#define deb print
// #define _GLIBCXX_DEBUG
#else
#define deb(...)
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
//！？！？
#define O print
//可変長引数で入力を受け取りつつ変数を宣言
inline void scan(){}
template<class Head,class... Tail>
inline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
//vectorのcin
template<typename T>
std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
//vectorのcout
template<typename T>
std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
//x,y,x,yを渡すとldで距離を返す
long double my_distance(long double xi,long double yi,long double xj,long double yj){return sqrt(abs((xi-xj)*(xi-xj))+abs((yi-yj)*(yi-yj)));}
//可変長引数のprint関数
void print(){cout << '\n';}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
//可変長引数のmin
template<class... T>
constexpr auto min(T... a){return min(initializer_list<common_type_t<T...>>{a...});}
//可変長引数のmax
template<class... T>
constexpr auto max(T... a){return max(initializer_list<common_type_t<T...>>{a...});}
template<typename T,typename U>inline bool chmax(T&a,U b){if(a<b){a=b;return 1;}return 0;}
template<typename T,typename U>inline bool chmin(T&a,U b){if(a>b){a=b;return 1;}return 0;}
template<typename T> inline T sum(vector<T>&a){T ret{};for(auto&i:a)ret+=i;return ret;}
template<typename T> inline T min(vector<T>&a){T ret=a[0];for(auto&i:a)chmin(ret,i);return ret;}
template<typename T> inline T max(vector<T>&a){T ret=a[0];for(auto&i:a)chmax(ret,i);return ret;}
template<typename T> inline int len(vector<T>&a){return a.size();}
inline int len(string&a){return a.size();}
// n次元配列の初期化。第２引数の型のサイズごとに初期化していく。
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){std::fill( (T*)array, (T*)(array+N), val );}
//こめんとを付け外ししてMODを切り替える
//ll MOD = INF;
// ll MOD = 1000000007;
ll MOD = 998244353;

//from:https://kenkoooo.hatenablog.com/entry/2016/11/30/163533 int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {std::ostream::sentry s(dest);if (s){__uint128_t tmp = value < 0 ? -value : value;char buffer[128];char *d = std::end(buffer);do{--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest;}
__int128 parsetoint128(string &s) {__int128 ret = 0;for (int i = 0; i < (int)s.length(); i++)if ('0' <= s[i] && s[i] <= '9')ret=10*ret+(__int128_t)(s[i]-'0');return ret;}

//回文判定 
bool iskaibun(string s){ll k = s.size();rep(i,0,k/2){if(s[i]!=s[k-1-i]){return false;}}return true;}

//二部グラフ判定 重みなしグラフを引数に取り、boolを返す
bool isbipartite_graph(vector<vector<ll>>&g){ll v = g.size();vector<ll>col(v,-1);vector<bool>used(v,false);bool ret = true;rep(i,v){if(used[i])continue;col[i]=0;[DFS([&](auto&&f,ll pos,ll pr)->void{if(used[pos])return;used[pos]=true;for(auto to:g[pos]){if(to==pr)continue;if(used[to]&&col[pos]==col[to]){ret = false;return;}if(used[to])continue;col[to]=col[pos]^1;f(f,to,pos);}}),&i]{DFS(DFS,i,-1);}();}return ret;}
//a~bの和 a<b
ll ran(ll a,ll b){return ((a+b)*(b-a+1))/2;}
//座圧する
ll zaatu(vector<ll>&A){map<ll,ll>m;for(auto&&x:A)m[x]=0;ll ret = 0;for(auto&&[key,val]:m)val=ret++;for(auto&&x:A)x=m[x];return ret;}
//約数列挙　引数に取った整数の約数のvectorを返す
vector<ll>enumdiv(ll n){vector<ll>s;for(ll i = 1;i*i<=n;i++){if(n%i==0){s.push_back(i);if(i*i!=n)s.push_back(n/i);}}return s;}
//トポロジカルソート グラフ、入次数カウント、頂点数を引数で渡すと、トポロジカルソートされた頂点列を返す
vector<ll> topo_sort(vector<vector<ll>>&G,vector<ll>&nyu_cnt,ll v){vector<ll>ret;priority_queue<ll,vector<ll>,greater<ll>>pq;rep(i,0,v){if(nyu_cnt[i]==0)pq.push(i);}while(!pq.empty()){ll pos = pq.top();pq.pop();for(ll i:G[pos]){nyu_cnt[i]--;if(nyu_cnt[i]==0)pq.push(i);}ret.push_back(pos);}return ret;}
//素因数分解 pair<素数、指数>のvectorを返す
vector<pair<ll,ll>> soinsu_bunkai(ll x){vector<pair<ll,ll>>ret;rep(i,2,sqrt(x)+1){if(x%i==0){ll cnt{};while(x%i==0){x/=i;cnt++;}ret.push_back({i,cnt});}}if(x!=1)ret.push_back({x,1});return ret;}
//二項係数MOD MODは上の方で設定、MAXまでのnCrをCOM(n,r)でとれる
const int MAX = 5000010;
ll fac[MAX], finv[MAX], invv[MAX];
void COMinit(){fac[0]=fac[1]=finv[0]=finv[1]=invv[1]=1;for(int i=2;i<MAX;i++){fac[i]=fac[i-1]*i%MOD;invv[i]=MOD-invv[MOD%i]*(MOD/i)%MOD;finv[i]=finv[i-1]*invv[i]%MOD;}}
ll COM(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;}
ll nPr(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[n-k]);}
//エラトステネスの篩　isprimeには素数かどうかが入っている
vector<bool> isprime;vector<int> Era(int n) {isprime.resize(n, true);vector<int> res;isprime[0] = false; isprime[1] = false;for (int i = 2; i < n; ++i) isprime[i] = true;for (int i = 2; i < n; ++i){if (isprime[i]) {res.push_back(i);for (int j = i*2; j < n; j += i) isprime[j] = false;}}return res;}
//Union-Find from https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/vi((b%2==0?b-1:b)+2-(a%2==0?a+1:a))/2er/union-find
class UnionFind{public:UnionFind()=default;explicit UnionFind(size_t n):m_parentsOrSize(n, -1){}int find(int i){if(m_parentsOrSize[i]<0){return i;}return(m_parentsOrSize[i]=find(m_parentsOrSize[i]));}void merge(int a,int b){a=find(a);b=find(b);if(a!=b){if(-m_parentsOrSize[a]<-m_parentsOrSize[b]){std::swap(a,b);}m_parentsOrSize[a]+=m_parentsOrSize[b];m_parentsOrSize[b]=a;}}bool connected(int a,int b){return (find(a)==find(b));}int size(int i){return -m_parentsOrSize[find(i)];}private:std::vector<int>m_parentsOrSize;};
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
ll dx[8] = {0,1,0,-1,-1,-1,1,1},dy[8]={1,0,-1,0,-1,1,-1,1};

ll p;
vector<pair<ll,ll>>soi;
bool solve();
void _main(){
[]{[]{[]{[]{[]{}();}();}();}();}();
	cin >> p;
	soi = soinsu_bunkai(p-1);
	int testcase = 1;
	cin >> testcase;
	for(;testcase--;){
		if(solve()){
			O(1);
			// O("Yes");
		}
		else{
			O(0);
			// O("-1");
			// O("No");
		}
	}
	cout<<flush;
[]{[]{[]{[]{[]{}();}();}();}();}();
}

// #include<atcoder/all>
// using namespace atcoder;
// using mint = modint998244353;
// using mint1 = modint1000000007;
__int128_t modpow(__int128_t x,__int128_t y){
	__int128_t now = x;
	__int128_t ret = 1;
	while(y>0){
		if(y&1){
			ret *= now;
			ret %= p;
		}
		now *= now;
		now %= p;
		y >>= 1ull;
	}
	return ret;
}
bool solve(){
	LL(n);
	vector<ll>a(n);cin >> a;
	LL(A);
	//Aの位数を求める。
	ll Ai = p-1;
	for(auto[num,val]:soi){
		while(Ai%num==0&&modpow(A,Ai/num)==1)Ai/=num;
	}
	rep(i,n){
		ll m = p-1;
		for(auto[num,val]:soi){
			while(m%num==0&&modpow(a[i],m/num)==1)m/=num;
		}
		deb(i,m,Ai,A,a[i]);
		if(m%Ai==0)return 1;
		if(Ai%m==0)Ai/=m;
	}
	return 0;
}
accuracy: 0.058823529411764705
time_ms: 470
memory_kb: 3408
final_rank: 16

code_snippet: using namespace std;
#include<bits/stdc++.h>
void _main();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(30);_main();return 0;}
typedef long long ll;typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef string str;
#define rep1(a)          for(ll i = 0; i < (a); i++)
#define rep2(i, a)       for(ll i = 0; i < (a); i++)
#define rep3(i, a, b)    for(ll i = (a); i < (b); i++)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define ALL(x) std::begin(x),std::end(x)
#define rALL(x) std::rbegin(x),std::rend(x)
#define INF ((1LL<<62)-(1LL<<31))
#define bit(x,i) (((x)>>(i))&1)
#define fi first
#define se second
#define pb push_back
#define Endl endl
#define spa " "
#define YesNo(x) cout<<(x?"Yes":"No")<<endl;
#define eps (1e-10)

//コンパイル時の引数にBLUEBERRYを渡すとdeb関数が使える
#ifdef BLUEBERRY
#define deb print
// #define _GLIBCXX_DEBUG
#else
#define deb(...)
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
//！？！？
#define O print
//可変長引数で入力を受け取りつつ変数を宣言
inline void scan(){}
template<class Head,class... Tail>
inline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
//vectorのcin
template<typename T>
std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
//vectorのcout
template<typename T>
std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
//x,y,x,yを渡すとldで距離を返す
long double my_distance(long double xi,long double yi,long double xj,long double yj){return sqrt(abs((xi-xj)*(xi-xj))+abs((yi-yj)*(yi-yj)));}
//可変長引数のprint関数
void print(){cout << '\n';}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
//可変長引数のmin
template<class... T>
constexpr auto min(T... a){return min(initializer_list<common_type_t<T...>>{a...});}
//可変長引数のmax
template<class... T>
constexpr auto max(T... a){return max(initializer_list<common_type_t<T...>>{a...});}
template<typename T,typename U>inline bool chmax(T&a,U b){if(a<b){a=b;return 1;}return 0;}
template<typename T,typename U>inline bool chmin(T&a,U b){if(a>b){a=b;return 1;}return 0;}
template<typename T> inline T sum(vector<T>&a){T ret{};for(auto&i:a)ret+=i;return ret;}
template<typename T> inline T min(vector<T>&a){T ret=a[0];for(auto&i:a)chmin(ret,i);return ret;}
template<typename T> inline T max(vector<T>&a){T ret=a[0];for(auto&i:a)chmax(ret,i);return ret;}
template<typename T> inline int len(vector<T>&a){return a.size();}
inline int len(string&a){return a.size();}
// n次元配列の初期化。第２引数の型のサイズごとに初期化していく。
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){std::fill( (T*)array, (T*)(array+N), val );}
//こめんとを付け外ししてMODを切り替える
//ll MOD = INF;
// ll MOD = 1000000007;
ll MOD = 998244353;

//from:https://kenkoooo.hatenablog.com/entry/2016/11/30/163533 int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {std::ostream::sentry s(dest);if (s){__uint128_t tmp = value < 0 ? -value : value;char buffer[128];char *d = std::end(buffer);do{--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest;}
__int128 parsetoint128(string &s) {__int128 ret = 0;for (int i = 0; i < (int)s.length(); i++)if ('0' <= s[i] && s[i] <= '9')ret=10*ret+(__int128_t)(s[i]-'0');return ret;}

//回文判定 
bool iskaibun(string s){ll k = s.size();rep(i,0,k/2){if(s[i]!=s[k-1-i]){return false;}}return true;}

//二部グラフ判定 重みなしグラフを引数に取り、boolを返す
bool isbipartite_graph(vector<vector<ll>>&g){ll v = g.size();vector<ll>col(v,-1);vector<bool>used(v,false);bool ret = true;rep(i,v){if(used[i])continue;col[i]=0;[DFS([&](auto&&f,ll pos,ll pr)->void{if(used[pos])return;used[pos]=true;for(auto to:g[pos]){if(to==pr)continue;if(used[to]&&col[pos]==col[to]){ret = false;return;}if(used[to])continue;col[to]=col[pos]^1;f(f,to,pos);}}),&i]{DFS(DFS,i,-1);}();}return ret;}
//a~bの和 a<b
ll ran(ll a,ll b){return ((a+b)*(b-a+1))/2;}
//座圧する
ll zaatu(vector<ll>&A){map<ll,ll>m;for(auto&&x:A)m[x]=0;ll ret = 0;for(auto&&[key,val]:m)val=ret++;for(auto&&x:A)x=m[x];return ret;}
//約数列挙　引数に取った整数の約数のvectorを返す
vector<ll>enumdiv(ll n){vector<ll>s;for(ll i = 1;i*i<=n;i++){if(n%i==0){s.push_back(i);if(i*i!=n)s.push_back(n/i);}}return s;}
//トポロジカルソート グラフ、入次数カウント、頂点数を引数で渡すと、トポロジカルソートされた頂点列を返す
vector<ll> topo_sort(vector<vector<ll>>&G,vector<ll>&nyu_cnt,ll v){vector<ll>ret;priority_queue<ll,vector<ll>,greater<ll>>pq;rep(i,0,v){if(nyu_cnt[i]==0)pq.push(i);}while(!pq.empty()){ll pos = pq.top();pq.pop();for(ll i:G[pos]){nyu_cnt[i]--;if(nyu_cnt[i]==0)pq.push(i);}ret.push_back(pos);}return ret;}
//素因数分解 pair<素数、指数>のvectorを返す
vector<pair<ll,ll>> soinsu_bunkai(ll x){vector<pair<ll,ll>>ret;rep(i,2,sqrt(x)+1){if(x%i==0){ll cnt{};while(x%i==0){x/=i;cnt++;}ret.push_back({i,cnt});}}if(x!=1)ret.push_back({x,1});return ret;}
//二項係数MOD MODは上の方で設定、MAXまでのnCrをCOM(n,r)でとれる
const int MAX = 5000010;
ll fac[MAX], finv[MAX], invv[MAX];
void COMinit(){fac[0]=fac[1]=finv[0]=finv[1]=invv[1]=1;for(int i=2;i<MAX;i++){fac[i]=fac[i-1]*i%MOD;invv[i]=MOD-invv[MOD%i]*(MOD/i)%MOD;finv[i]=finv[i-1]*invv[i]%MOD;}}
ll COM(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;}
ll nPr(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[n-k]);}
//エラトステネスの篩　isprimeには素数かどうかが入っている
vector<bool> isprime;vector<int> Era(int n) {isprime.resize(n, true);vector<int> res;isprime[0] = false; isprime[1] = false;for (int i = 2; i < n; ++i) isprime[i] = true;for (int i = 2; i < n; ++i){if (isprime[i]) {res.push_back(i);for (int j = i*2; j < n; j += i) isprime[j] = false;}}return res;}
//Union-Find from https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/vi((b%2==0?b-1:b)+2-(a%2==0?a+1:a))/2er/union-find
class UnionFind{public:UnionFind()=default;explicit UnionFind(size_t n):m_parentsOrSize(n, -1){}int find(int i){if(m_parentsOrSize[i]<0){return i;}return(m_parentsOrSize[i]=find(m_parentsOrSize[i]));}void merge(int a,int b){a=find(a);b=find(b);if(a!=b){if(-m_parentsOrSize[a]<-m_parentsOrSize[b]){std::swap(a,b);}m_parentsOrSize[a]+=m_parentsOrSize[b];m_parentsOrSize[b]=a;}}bool connected(int a,int b){return (find(a)==find(b));}int size(int i){return -m_parentsOrSize[find(i)];}private:std::vector<int>m_parentsOrSize;};
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
ll dx[8] = {0,1,0,-1,-1,-1,1,1},dy[8]={1,0,-1,0,-1,1,-1,1};

ll p;
vector<pair<ll,ll>>soi;
bool solve();
void _main(){
[]{[]{[]{[]{[]{}();}();}();}();}();
	cin >> p;
	soi = soinsu_bunkai(p-1);
	int testcase = 1;
	cin >> testcase;
	for(;testcase--;){
		if(solve()){
			O(1);
			// O("Yes");
		}
		else{
			O(0);
			// O("-1");
			// O("No");
		}
	}
	cout<<flush;
[]{[]{[]{[]{[]{}();}();}();}();}();
}

// #include<atcoder/all>
// using namespace atcoder;
// using mint = modint998244353;
// using mint1 = modint1000000007;
__int128_t modpow(__int128_t x,__int128_t y){
	__int128_t now = x;
	__int128_t ret = 1;
	while(y>0){
		if(y&1){
			ret *= now;
			ret %= p;
		}
		now *= now;
		now %= p;
		y >>= 1ull;
	}
	return ret;
}
bool solve(){
	LL(n);
	vector<ll>a(n);cin >> a;
	LL(A);
	//Aの位数を求める。
	ll Ai = p-1;
	for(auto[num,val]:soi){
		while(Ai%num==0&&modpow(A,Ai/num)==1)Ai/=num;
	}
	rep(i,n){
		ll m = p-1;
		for(auto[num,val]:soi){
			while(m%num==0&&modpow(a[i],m/num)==1)m/=num;
		}
		deb(i,m,Ai,A,a[i]);
		if(m%Ai==0)return 1;
		if(Ai%m)Ai/=m;
	}
	return 0;
}
accuracy: 0.058823529411764705
time_ms: 470
memory_kb: 3472
final_rank: 18

code_snippet: using namespace std;
#include<bits/stdc++.h>
void _main();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(30);_main();return 0;}
typedef long long ll;typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef string str;
#define rep1(a)          for(ll i = 0; i < (a); i++)
#define rep2(i, a)       for(ll i = 0; i < (a); i++)
#define rep3(i, a, b)    for(ll i = (a); i < (b); i++)
#define rep4(i, a, b, c) for(ll i = (a); i < (b); i += (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define ALL(x) std::begin(x),std::end(x)
#define rALL(x) std::rbegin(x),std::rend(x)
#define INF ((1LL<<62)-(1LL<<31))
#define bit(x,i) (((x)>>(i))&1)
#define fi first
#define se second
#define pb push_back
#define Endl endl
#define spa " "
#define YesNo(x) cout<<(x?"Yes":"No")<<endl;
#define eps (1e-10)

//コンパイル時の引数にBLUEBERRYを渡すとdeb関数が使える
#ifdef BLUEBERRY
#define deb print
// #define _GLIBCXX_DEBUG
#else
#define deb(...)
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif
//！？！？
#define O print
//可変長引数で入力を受け取りつつ変数を宣言
inline void scan(){}
template<class Head,class... Tail>
inline void scan(Head&head,Tail&... tail){std::cin>>head;scan(tail...);}
#define LL(...) ll __VA_ARGS__;scan(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;scan(__VA_ARGS__)
//vectorのcin
template<typename T>
std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
//vectorのcout
template<typename T>
std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
//x,y,x,yを渡すとldで距離を返す
long double my_distance(long double xi,long double yi,long double xj,long double yj){return sqrt(abs((xi-xj)*(xi-xj))+abs((yi-yj)*(yi-yj)));}
//可変長引数のprint関数
void print(){cout << '\n';}
template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
//可変長引数のmin
template<class... T>
constexpr auto min(T... a){return min(initializer_list<common_type_t<T...>>{a...});}
//可変長引数のmax
template<class... T>
constexpr auto max(T... a){return max(initializer_list<common_type_t<T...>>{a...});}
template<typename T,typename U>inline bool chmax(T&a,U b){if(a<b){a=b;return 1;}return 0;}
template<typename T,typename U>inline bool chmin(T&a,U b){if(a>b){a=b;return 1;}return 0;}
template<typename T> inline T sum(vector<T>&a){T ret{};for(auto&i:a)ret+=i;return ret;}
template<typename T> inline T min(vector<T>&a){T ret=a[0];for(auto&i:a)chmin(ret,i);return ret;}
template<typename T> inline T max(vector<T>&a){T ret=a[0];for(auto&i:a)chmax(ret,i);return ret;}
template<typename T> inline int len(vector<T>&a){return a.size();}
inline int len(string&a){return a.size();}
// n次元配列の初期化。第２引数の型のサイズごとに初期化していく。
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){std::fill( (T*)array, (T*)(array+N), val );}
//こめんとを付け外ししてMODを切り替える
//ll MOD = INF;
// ll MOD = 1000000007;
ll MOD = 998244353;

//from:https://kenkoooo.hatenablog.com/entry/2016/11/30/163533 int128
std::ostream &operator<<(std::ostream &dest, __int128_t value) {std::ostream::sentry s(dest);if (s){__uint128_t tmp = value < 0 ? -value : value;char buffer[128];char *d = std::end(buffer);do{--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest;}
__int128 parsetoint128(string &s) {__int128 ret = 0;for (int i = 0; i < (int)s.length(); i++)if ('0' <= s[i] && s[i] <= '9')ret=10*ret+(__int128_t)(s[i]-'0');return ret;}

//回文判定 
bool iskaibun(string s){ll k = s.size();rep(i,0,k/2){if(s[i]!=s[k-1-i]){return false;}}return true;}

//二部グラフ判定 重みなしグラフを引数に取り、boolを返す
bool isbipartite_graph(vector<vector<ll>>&g){ll v = g.size();vector<ll>col(v,-1);vector<bool>used(v,false);bool ret = true;rep(i,v){if(used[i])continue;col[i]=0;[DFS([&](auto&&f,ll pos,ll pr)->void{if(used[pos])return;used[pos]=true;for(auto to:g[pos]){if(to==pr)continue;if(used[to]&&col[pos]==col[to]){ret = false;return;}if(used[to])continue;col[to]=col[pos]^1;f(f,to,pos);}}),&i]{DFS(DFS,i,-1);}();}return ret;}
//a~bの和 a<b
ll ran(ll a,ll b){return ((a+b)*(b-a+1))/2;}
//座圧する
ll zaatu(vector<ll>&A){map<ll,ll>m;for(auto&&x:A)m[x]=0;ll ret = 0;for(auto&&[key,val]:m)val=ret++;for(auto&&x:A)x=m[x];return ret;}
//約数列挙　引数に取った整数の約数のvectorを返す
vector<ll>enumdiv(ll n){vector<ll>s;for(ll i = 1;i*i<=n;i++){if(n%i==0){s.push_back(i);if(i*i!=n)s.push_back(n/i);}}return s;}
//トポロジカルソート グラフ、入次数カウント、頂点数を引数で渡すと、トポロジカルソートされた頂点列を返す
vector<ll> topo_sort(vector<vector<ll>>&G,vector<ll>&nyu_cnt,ll v){vector<ll>ret;priority_queue<ll,vector<ll>,greater<ll>>pq;rep(i,0,v){if(nyu_cnt[i]==0)pq.push(i);}while(!pq.empty()){ll pos = pq.top();pq.pop();for(ll i:G[pos]){nyu_cnt[i]--;if(nyu_cnt[i]==0)pq.push(i);}ret.push_back(pos);}return ret;}
//素因数分解 pair<素数、指数>のvectorを返す
vector<pair<ll,ll>> soinsu_bunkai(ll x){vector<pair<ll,ll>>ret;rep(i,2,sqrt(x)+1){if(x%i==0){ll cnt{};while(x%i==0){x/=i;cnt++;}ret.push_back({i,cnt});}}if(x!=1)ret.push_back({x,1});return ret;}
//二項係数MOD MODは上の方で設定、MAXまでのnCrをCOM(n,r)でとれる
const int MAX = 5000010;
ll fac[MAX], finv[MAX], invv[MAX];
void COMinit(){fac[0]=fac[1]=finv[0]=finv[1]=invv[1]=1;for(int i=2;i<MAX;i++){fac[i]=fac[i-1]*i%MOD;invv[i]=MOD-invv[MOD%i]*(MOD/i)%MOD;finv[i]=finv[i-1]*invv[i]%MOD;}}
ll COM(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;}
ll nPr(int n,int k){if(n<k)return 0;if(n<0||k<0)return 0;if(k==0)return 1;return fac[n]*(finv[n-k]);}
//エラトステネスの篩　isprimeには素数かどうかが入っている
vector<bool> isprime;vector<int> Era(int n) {isprime.resize(n, true);vector<int> res;isprime[0] = false; isprime[1] = false;for (int i = 2; i < n; ++i) isprime[i] = true;for (int i = 2; i < n; ++i){if (isprime[i]) {res.push_back(i);for (int j = i*2; j < n; j += i) isprime[j] = false;}}return res;}
//Union-Find from https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/vi((b%2==0?b-1:b)+2-(a%2==0?a+1:a))/2er/union-find
class UnionFind{public:UnionFind()=default;explicit UnionFind(size_t n):m_parentsOrSize(n, -1){}int find(int i){if(m_parentsOrSize[i]<0){return i;}return(m_parentsOrSize[i]=find(m_parentsOrSize[i]));}void merge(int a,int b){a=find(a);b=find(b);if(a!=b){if(-m_parentsOrSize[a]<-m_parentsOrSize[b]){std::swap(a,b);}m_parentsOrSize[a]+=m_parentsOrSize[b];m_parentsOrSize[b]=a;}}bool connected(int a,int b){return (find(a)==find(b));}int size(int i){return -m_parentsOrSize[find(i)];}private:std::vector<int>m_parentsOrSize;};
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
ll dx[8] = {0,1,0,-1,-1,-1,1,1},dy[8]={1,0,-1,0,-1,1,-1,1};

ll p;
vector<pair<ll,ll>>soi;
bool solve();
void _main(){
[]{[]{[]{[]{[]{}();}();}();}();}();
	cin >> p;
	soi = soinsu_bunkai(p-1);
	int testcase = 1;
	cin >> testcase;
	for(;testcase--;){
		if(solve()){
			O(1);
			// O("Yes");
		}
		else{
			O(0);
			// O("-1");
			// O("No");
		}
	}
	cout<<flush;
[]{[]{[]{[]{[]{}();}();}();}();}();
}

// #include<atcoder/all>
// using namespace atcoder;
// using mint = modint998244353;
// using mint1 = modint1000000007;
__int128_t modpow(__int128_t x,__int128_t y){
	__int128_t now = x;
	__int128_t ret = 1;
	while(y>0){
		if(y&1){
			ret *= now;
			ret %= p;
		}
		now *= now;
		now %= p;
		y >>= 1ull;
	}
	return ret;
}
bool solve(){
	LL(n);
	vector<ll>a(n);cin >> a;
	LL(A);
	//Aの位数を求める。
	ll Ai = p-1;
	for(auto[num,val]:soi){
		while(Ai%num==0&&modpow(A,Ai/num)==1)Ai/=num;
	}
	rep(i,n){
		ll m = p-1;
		for(auto[num,val]:soi){
			while(m%num==0&&modpow(a[i],m/num)==1)m/=num;
		}
		if(m%Ai==0)return 1;
	}
	return 0;
}
accuracy: 0.058823529411764705
time_ms: 470
memory_kb: 3476
final_rank: 19

code_snippet: #include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>

int main()
{
    using namespace std;
    using lint = long long;
    lint p, t;
    cin >> p >> t;
    vector<pair<lint, int>> pe;
    lint pp = p - 1;
    {
        lint pp_ = pp;
        for (lint pi = 2; pi * pi <= pp_; ++pi) {
            if (pp_ % pi == 0) {
                int e = 0;
                while (pp_ % pi == 0) {
                    pp_ /= pi;
                    ++e;
                }
                pe.emplace_back(pi, e);
            }
        }
        if (pp_ > 1) pe.emplace_back(pp_, 1);
    }
    auto mul = [&](lint a, lint b) { return a * b % p; };
    auto modpow = [&](lint a, lint e) {
        lint ans = 1;
        while (e) {
            if (e & 1) {
                ans = mul(ans, a);
            }
            e >>= 1;
            a = mul(a, a);
        }
        return ans;
    };
    auto get_ord = [&](lint x) {
        lint m = pp;
        for (auto [pi, ei] : pe) {
            for (int i = 0; i < ei; ++i) {
                if (modpow(x, m / pi) == 1)
                    m /= pi;
                else
                    break;
            }
        }
        return m;
    };
    for (int ti = 0; ti < t; ++ti) {
        int n;
        cin >> n;
        vector<lint> g(n);
        for (int i = 0; i < n; ++i) cin >> g[i];
        lint a;
        cin >> a;
        lint e_gcd = pp;
        for (lint gi: g) {
            lint oi = get_ord(gi);
            e_gcd = gcd(e_gcd, pp / oi);
        }
        lint ao = get_ord(a);
        printf("%d\n", (pp / ao) % e_gcd == 0 ? 1 : 0);
    }
}
accuracy: 1
time_ms: 630
memory_kb: 3876
final_rank: 5

code_snippet: // verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3062

#include<bits/stdc++.h>
using namespace std;

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T>
T mod_pow(T a,long long n,T mod){
  using ll = long long;
  T res(1);
  while(n){
    if(n&1) res=(ll)res*a%mod;
    a=(ll)a*a%mod;
    n>>=1;
  }
  return res;
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;

#define call_from_test
#include "pow.cpp"
#undef call_from_test

#endif
//BEGIN CUT HERE
template<typename T>
T order(T x,T MOD){
  static map<T, vector<T>> dp;
  static map<T, T> phi;

  vector<T> &ps=dp[MOD];
  if(ps.empty()){
    T res=MOD,n=MOD;
    for(T i=2;i*i<=n;i++){
      if(n%i) continue;
      while(n%i==0) n/=i;
      res=res/i*(i-1);
    }
    if(n!=1) res=res/n*(n-1);
    phi[MOD]=res;

    for(T i=2;i*i<=res;i++){
      if(res%i) continue;
      while(res%i==0) res/=i;
      ps.emplace_back(i);
    }
    if(res!=1) ps.emplace_back(res);
  }

  T res=phi[MOD];
  for(T p:ps){
    while(res%p==0){
      if(mod_pow(x,res/p,MOD)!=1) break;
      res/=p;
    }
  }
  return res;
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);
  const char newl = '\n';

  int MOD;
  cin>>MOD;

  int T;
  cin>>T;
  while(T--){
    int n;
    cin>>n;

    vector<int> gs(n);
    for(int i=0;i<n;i++) cin>>gs[i];

    int a;
    cin>>a;

    if(a==1){
      cout<<1<<newl;
      continue;
    }

    if(gs==vector<int>(n,1)){
      cout<<0<<newl;
      continue;
    }
    sort(gs.rbegin(),gs.rend());
    while(gs.back()==1) gs.pop_back();

    using ll = long long;
    int res=order<ll>(gs[0],MOD);
    for(int x:gs) res=lcm(res,order<ll>(x,MOD));

    cout<<(res%order<ll>(a,MOD)==0?1:0)<<newl;
  }
  return 0;
}
accuracy: 1
time_ms: 770
memory_kb: 3848
final_rank: 8

code_snippet: // verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3062

#include<bits/stdc++.h>
using namespace std;

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T>
T mod_pow(T a,long long n,T mod){
  using ll = long long;
  T res(1);
  while(n){
    if(n&1) res=(ll)res*a%mod;
    a=(ll)a*a%mod;
    n>>=1;
  }
  return res;
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;

#define call_from_test
#include "pow.cpp"
#undef call_from_test

#endif
//BEGIN CUT HERE
template<typename T>
T order(T x,T MOD){
  static map<T, vector<T>> dp;
  static map<T, T> phi;

  vector<T> &ps=dp[MOD];
  if(ps.empty()){
    T res=MOD,n=MOD;
    for(T i=2;i*i<=n;i++){
      if(n%i) continue;
      while(n%i==0) n/=i;
      res=res/i*(i-1);
    }
    if(n!=1) res=res/n*(n-1);
    phi[MOD]=res;

    for(T i=2;i*i<=res;i++){
      if(res%i) continue;
      while(res%i==0) res/=i;
      ps.emplace_back(i);
    }
    if(res!=1) ps.emplace_back(res);
  }
  if(MOD==2147483579) exit(0);

  T res=phi[MOD];
  for(T p:ps){
    while(res%p==0){
      if(mod_pow(x,res/p,MOD)!=1) break;
      res/=p;
    }
  }
  return res;
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);
  const char newl = '\n';

  int MOD;
  cin>>MOD;

  int T;
  cin>>T;
  while(T--){
    int n;
    cin>>n;

    vector<int> gs(n);
    for(int i=0;i<n;i++) cin>>gs[i];

    int a;
    cin>>a;

    if(a==1){
      cout<<1<<newl;
      continue;
    }

    if(gs==vector<int>(n,1)){
      cout<<0<<newl;
      continue;
    }
    sort(gs.rbegin(),gs.rend());
    while(gs.back()==1) gs.pop_back();

    int res=order(gs[0],MOD);
    for(int x:gs) res=lcm(res,order(x,MOD));

    cout<<(res%order(a,MOD)==0?1:0)<<newl;
  }
  return 0;
}
accuracy: 0.3235294117647059
time_ms: 3880
memory_kb: 3404
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;

//BEGIN CUT HERE
template<typename T>
map<T, T> factorize(T x){
  map<T, T> res;
  for(T i=2;i*i<=x;i++){
    while(x%i==0){
      x/=i;
      res[i]++;
    }
  }
  if(x!=1) res[x]++;
  return res;
}

template<typename T>
T mpow(T x,T n,T MOD){
  T res(1);
  while(n){
    if(n&1) res=res*x%MOD;
    x=x*x%MOD;
    n>>=1;
  }
  return res;
}

template<typename T>
T order(T x,T MOD){
  static map<T, vector<T>> dp;
  vector<T> &ps=dp[MOD];
  if(ps.empty()){
    auto fs=factorize(MOD-1);
    for(auto p:fs) ps.emplace_back(p.first);
  }

  T res=MOD-1;
  for(T p:ps){
    while(res%p==0){
      if(mpow(x,res/p,MOD)!=1) break;
      res/=p;
    }
  }
  return res;
}
//END CUT HERE
//INSERT ABOVE HERE
signed AOJ_3062(){
  using ll = long long;
  ll MOD;
  cin>>MOD;

  int T;
  cin>>T;
  while(T--){
    ll n;
    cin>>n;

    vector<ll> g(n);
    for(ll i=0;i<n;i++) cin>>g[i];

    ll a;
    cin>>a;

    if(a==1){
      cout<<1<<"\n";
      continue;
    }

    sort(g.rbegin(),g.rend());
    if(g[0]==1){
      cout<<0<<"\n";
      continue;
    }
    while(g.back()==1) g.pop_back();

    auto mlcm=[&](ll a,ll b){return a/__gcd(a,b)*b;};

    ll res=order(g[0],MOD);
    for(ll x:g) res=mlcm(res,order(x,MOD));

    cout<<(res%order(a,MOD)==0?1:0)<<"\n";
  }
  cout<<flush;
  return 0;
}
/*
  verified on 2019/06/16
  http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3062
*/

signed main(){
  AOJ_3062();
  return 0;
}
accuracy: 1
time_ms: 950
memory_kb: 3596
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

long long MOD;

template<typename T>
struct Mint{
  T v;
  Mint():v(0){}
  Mint(signed v):v(v){}
  Mint(long long t){v=t%MOD;if(v<0) v+=MOD;}

  Mint pow(long long k){
    Mint res(1),tmp(v);
    while(k){
      if(k&1) res*=tmp;
      tmp*=tmp;
      k>>=1;
    }
    return res;
  }
  
  Mint inv(){return pow(MOD-2);}
  
  Mint& operator+=(Mint a){v+=a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator-=(Mint a){v+=MOD-a.v;if(v>=MOD)v-=MOD;return *this;}
  Mint& operator*=(Mint a){v=1LL*v*a.v%MOD;return *this;}
  Mint& operator/=(Mint a){return (*this)*=a.inv();}
  
  Mint operator+(Mint a) const{return Mint(v)+=a;};
  Mint operator-(Mint a) const{return Mint(v)-=a;};
  Mint operator*(Mint a) const{return Mint(v)*=a;};
  Mint operator/(Mint a) const{return Mint(v)/=a;};

  Mint operator-(){return v?MOD-v:v;}

  bool operator==(const Mint a)const{return v==a.v;}
  bool operator!=(const Mint a)const{return v!=a.v;}
  bool operator <(const Mint a)const{return v <a.v;}

};

struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;


template<typename T> 
map<T, Int> factorize(T x){
  map<T, Int> res;
  for(Int i=2;i*i<=x;i++){
    while(x%i==0){
      x/=i;
      res[i]++;
    }
  }
  if(x!=1) res[x]++;
  return res;
}

//INSERT ABOVE HERE
using M = Mint<Int>;
vector<Int> ps;
Int ord(Int x){
  Int res=MOD-1;
  for(Int p:ps){
    while(res%p==0){
      M v(x);
      if(v.pow(res/p).v!=1) break;
      res/=p;
    }
  }
  //cout<<x<<":"<<res<<endl;
  return res;
}

Int mlcm(Int a,Int b){
  return a/__gcd(a,b)*b;
}

void solve(){
  Int n;
  cin>>n;
  vector<Int> g(n);
  for(Int i=0;i<n;i++) cin>>g[i];
  Int a;
  cin>>a;
  if(a==1){
    cout<<1<<"\n";
    return;
  }
  
  sort(g.rbegin(),g.rend());
  if(g[0]==1){    
    cout<<0<<"\n";
    return;
  }
  while(g.back()==1) g.pop_back();
  
  Int res=ord(g[0]);
  for(Int x:g) res=mlcm(res,ord(x));
  
  cout<<(res%ord(a)==0?1:0)<<"\n";
}

signed main(){
  cin>>MOD;
  auto d=factorize(MOD-1);
  for(auto p:d)
    ps.emplace_back(p.first);
  
  Int T;
  cin>>T;
  while(T--) solve();
  cout<<flush;
  return 0;
}
accuracy: 1
time_ms: 1020
memory_kb: 3680
final_rank: 10

code_snippet: #include <cstdio>
#include <cstdint>
#include <vector>
#include <algorithm>
#include <map>
#include <utility>

std::map<intmax_t, intmax_t> factor(intmax_t n) {
  std::map<intmax_t, intmax_t> res;
  for (intmax_t i = 2; i*i <= n; ++i) {
    while (n % i == 0) {
      ++res[i];
      n /= i;
    }
  }
  if (n > 1) ++res[n];
  return res;
}

template <class Tp>
Tp modpow(Tp base, intmax_t iexp, Tp mod) {
  Tp res = 1;
  for (Tp dbl = base; iexp; iexp >>= 1) {
    if (iexp & 1) res = res * dbl % mod;
    dbl = dbl * dbl % mod;
  }
  return res;
}

template <class Tp>
Tp gcd(Tp m, Tp n) {
  while (n) std::swap(m %= n, n);
  return m;
}

template <class Tp>
Tp lcm(Tp m, Tp n) {
  return m / gcd(m, n) * n;
}

intmax_t ord(intmax_t g, intmax_t p, const std::map<intmax_t, intmax_t>& f) {
  intmax_t q = p-1;
  for (const auto& pp: f) {
    for (intmax_t i = 0; i < pp.second; ++i) {
      intmax_t e = pp.first;
      if (modpow(g, q/e, p) == 1)
        q /= e;
    }
  }
  return q;
}

int main() {
  intmax_t P;
  int T;
  scanf("%jd %d", &P, &T);

  auto f = factor(P-1);
  for (int i = 0; i < T; ++i) {
    size_t g;
    scanf("%zu", &g);

    intmax_t ords = 1;
    for (size_t j = 0; j < g; ++j) {
      intmax_t gi;
      scanf("%jd", &gi);
      ords = lcm(ords, ord(gi, P, f));
    }

    intmax_t a;
    scanf("%jd", &a);

    printf("%d\n", (ords % ord(a, P, f) == 0));
  }
}
accuracy: 1
time_ms: 2130
memory_kb: 2800
final_rank: 11

code_snippet: #include <cstdio>
#include <cstdint>
#include <vector>
#include <algorithm>
#include <map>
#include <utility>

std::map<intmax_t, intmax_t> factor(intmax_t n) {
  std::map<intmax_t, intmax_t> res;
  for (intmax_t i = 2; i*i <= n; ++i) {
    while (n % i == 0) {
      ++res[i];
      n /= i;
    }
  }
  if (n > 1) ++res[n];
  return res;
}

template <class Tp>
Tp modpow(Tp base, intmax_t iexp, Tp mod) {
  Tp res = 1;
  for (Tp dbl = base; iexp; iexp >>= 1) {
    if (iexp & 1) res = res * dbl % mod;
    dbl = dbl * dbl % mod;
  }
  return res;
}

template <class Tp>
Tp gcd(Tp m, Tp n) {
  while (n) std::swap(m %= n, n);
  return m;
}

template <class Tp>
Tp lcm(Tp m, Tp n) {
  return m / gcd(m, n) * n;
}

intmax_t ord(intmax_t g, intmax_t p, const std::map<intmax_t, intmax_t> f) {
  intmax_t q = p-1;
  for (const auto& pp: f) {
    for (intmax_t i = 0; i < pp.second; ++i) {
      intmax_t e = pp.first;
      if (modpow(g, q/e, p) == 1)
        q /= e;
    }
  }
  return q;
}

int main() {
  intmax_t P;
  int T;
  scanf("%jd %d", &P, &T);

  auto f = factor(P-1);
  for (int i = 0; i < T; ++i) {
    size_t g;
    scanf("%zu", &g);

    intmax_t ords = 1;
    for (size_t j = 0; j < g; ++j) {
      intmax_t gi;
      scanf("%jd", &gi);
      ords = lcm(ords, ord(gi, P, f));
    }

    intmax_t a;
    scanf("%jd", &a);

    printf("%d\n", (ords % ord(a, P, f) == 0));
  }
}
accuracy: 1
time_ms: 2150
memory_kb: 2800
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcountll

#define INF 1e16

ll mod_pow(ll a,ll n,ll m){
  ll res=1;
  while(n>0){
    if(n&1)res=res*a%m;
    a=a*a%m;
    n>>=1;
  }
  return res;
}

ll calc_order(ll X, const vector<P>& ps, ll M){
  ll g = 1;
  rep(i, ps.size()){
    ll mx = 0, r = M - 1;
    rep(j, ps[i].se){
      r /= ps[i].fi;
      if(mod_pow(X, r, M) != 1){
        mx = ps[i].se - j; break;
      }
    }
    ll t = mod_pow(ps[i].fi, mx, M);
    g *= t;
  }
  return g;
}

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  ll M,T;
  cin>>M>>T;

  vector<P> ps;
  ll tmp=M-1;
  for(ll i=2;i*i<=tmp;i++){
    if(tmp%i!=0)continue;
    P p=P(i,0);
    while(tmp%i==0){
      tmp/=i; p.se++;
    }
    ps.push_back(p);
  }
  if(tmp!=1){
    P p=P(tmp,1);
    ps.push_back(p);
  }

  while(T--){
    int N;
    cin>>N;
    ll a=-1,b=0;
    rep(i,N){
      ll X;
      cin>>X;
      b=__gcd(b,(M-1)/calc_order(X,ps,M));
    }
    {
      ll A;
      cin>>A;
      a=(M-1)/calc_order(A,ps,M);
    }
    if(a%b==0)cout<<1<<endl;
    else cout<<0<<endl;
  }

  return 0;
}
accuracy: 1
time_ms: 770
memory_kb: 3196
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcountll

#define INF 1e16

ll mod_pow(ll a,ll n,ll m){
  ll res=1;
  while(n>0){
    if(n&1)res=res*a%m;
    a=a*a%m;
    n>>=1;
  }
  return res;
}

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  ll M,T;
  cin>>M>>T;

  vector<P> ps;
  ll tmp=M-1;
  for(ll i=2;i*i<=tmp;i++){
    if(tmp%i!=0)continue;
    P p=P(i,0);
    while(tmp%i==0){
      tmp/=i; p.se++;
    }
    ps.push_back(p);
  }
  if(tmp!=1){
    P p=P(tmp,1);
    ps.push_back(p);
  }

  while(T--){
    int N;
    cin>>N;
    ll a=-1,b=0;
    rep(i,N){
      ll X;
      cin>>X;
      ll g=1;
      rep(j,ps.size()){
        ll mx=0,r=M-1;
        rep(k,ps[j].se){
          r/=ps[j].fi;
          if(mod_pow(X,r,M)!=1){
            mx=ps[j].se-k; break;
          }
        }
        ll t=mod_pow(ps[j].fi,mx,M);
        g*=t;
      }
      b=__gcd(b,(M-1)/g);
    }
    {
      ll A;
      cin>>A;
      ll g=0;
      rep(j,ps.size()){
        ll mn=ps[j].se,r=M-1;
        rep(k,ps[j].se){
          r/=ps[j].fi;
          if(mod_pow(A,r,M)!=1){
            mn=k; break;
          }
        }
        ll t=mod_pow(ps[j].fi,mn,M);
        g=__gcd(g,((M-1)/mod_pow(ps[j].fi,ps[j].se,M))*t);
      }
      a=g;
    }
    if(a%b==0)cout<<1<<endl;
    else cout<<0<<endl;
  }

  return 0;
}
accuracy: 1
time_ms: 820
memory_kb: 3196
final_rank: 7