#include using namespace std; using ll = long long; ll mod; //const ll mod = 998'244'353; //const ll mod = 1'000'000'007; //const ll mod = 67'280'421'310'721; struct mint{ long long x; mint(long long x=0):x((x%mod+mod)%mod){} mint operator-() const{ return mint(-x); } mint& operator+=(const mint& a){ if((x+=a.x)>=mod)x-=mod; return *this; } mint& operator-=(const mint& a){ if((x+=mod-a.x)>=mod)x-=mod; return *this; } mint& operator*=(const mint& a){ (x *= a.x) %= mod; return *this; } mint operator+(const mint& a) const{ mint res(*this); return res+=a; } mint operator-(const mint& a) const{ mint res(*this); return res-=a; } mint operator*(const mint& a) const{ mint res(*this); return res*=a; } mint pow(long long n) const { assert(0 <= n); mint a = *this, r = 1; while (n) { if (n & 1) r *= a; a *= a; n >>= 1; } return r; } mint inv() const{ return pow(mod-2); } mint& operator/=(const mint& a){ return (*this)*=a.inv(); } mint operator/(const mint& a) const { mint res(*this); return res/=a; } friend ostream& operator<<(ostream& os, const mint& m){ os << m.x; return os; } bool operator==(const mint& a) const { return x == a.x; } bool operator<(const mint& a) const{ return x < a.x; } }; template< typename T > vector> mattimes(vector> &A,vector> &B){ assert(A.size()==B.size()); int n = A.size(); vector> res(n,vector(n,0)); for(int i=0;i vector mattimes(vector> &A,vector &B){ assert(A.size()==B.size()); int n = A.size(); vector res(n,0); for(int i=0;i vector> matpow(vector> a,ll k){ int n = a.size(); vector> res(n,vector(n,0)); for(int i=0;i>=1){ if(k&1) res = mattimes(res,a); a = mattimes(a,a); } return res; } ll gcd(ll a,ll b){ if(b) return gcd(b,a%b); return a; } int64_t euler_phi(int64_t n) { int64_t ret = n; for(int64_t i = 2; i * i <= n; i++) { if(n % i == 0) { ret -= ret / i; while(n % i == 0) n /= i; } } if(n > 1) ret -= ret / n; return ret; } int main(){ int n; cin>>n>>mod; vector> a(3,vector(3,0)); for(int i = 0;i<3;i++){ for(int j = 0;j<3;j++){ ll b; cin>>b; a[i][j] = b; } } mint now = a[0][0] * a[1][1] * a[2][2] + a[0][1] * a[1][2] * a[2][0] + a[0][2] * a[1][0] * a[2][1]; now -= a[0][2] * a[1][1] * a[2][0] + a[0][1] * a[1][0] * a[2][2] + a[0][0]*a[1][2]*a[2][1]; now = now.pow(n); ll x = now.x; if(x==0||gcd(mod,x)!=1){ if(x==0) cout<<0<