#include using namespace std; #include using namespace atcoder; #define rep(i, n) for(int i=0;i<(n);++i) #define rep1(i, n) for(int i=1;i<=(n);i++) #define ll long long using mint = modint; using P = pair; using lb = long double; using T = tuple; #ifdef LOCAL # include # define dbg(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__) #else # define dbg(...) (static_cast(0)) #endif template struct Matrix { int h, w; vector> d; Matrix() {} //初期化のときは Matrix<> a(h, w) Matrix(int h, int w, T val=0): h(h), w(w), d(h, vector(w,val)) {} Matrix& unit() { assert(h == w); rep(i,h) d[i][i] = 1; return *this; } const vector& operator[](int i) const { return d[i];} vector& operator[](int i) { return d[i];} Matrix operator*(const Matrix& a) const { assert(w == a.h); Matrix r(h, a.w); rep(i,h)rep(k,w)rep(j,a.w) { r[i][j] += d[i][k]*a[k][j]; } return r; } //Matcix<> newa = a.pow(k)と使う Matrix pow(long long t) const { assert(h == w); if (!t) return Matrix(h,h).unit(); if (t == 1) return *this; Matrix r = pow(t>>1); r = r*r; if (t&1) r = r*(*this); return r; } }; int main() { int n, b; cin >> n >> b; // mint::set_mod(b); Matrix a(3,3); rep(i,3)rep(j,3){ int c; cin >> c; a[i][j] = c; } ll ans = 0; ans += a[0][0] * (a[1][1]*a[2][2]-a[1][2]*a[2][1]); ans -= a[0][1] * (a[1][0]*a[2][2]-a[2][0]*a[1][2]); ans += a[0][2] * (a[1][0]*a[2][1]-a[2][0]*a[1][1]); if(ans==0){ cout << 0 << endl; } else{ ans = abs(ans); cout << pow_mod(ans, n, b) << endl; } return 0; }