N, B = map(int, input().split()) A = [] for i in range(3): A.append(list(map(int, input().split()))) def det(M): v = 0 v += M[0][0] * M[1][1] * M[2][2] v += M[0][1] * M[1][2] * M[2][0] v += M[0][2] * M[1][0] * M[2][1] v -= M[0][2] * M[1][1] * M[2][0] v -= M[0][1] * M[1][0] * M[2][2] v -= M[0][0] * M[1][2] * M[2][1] return v print(pow(det(A), N, B))