n, b = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(3)] def mul(X, Y): res = [[0] * 3 for _ in range(3)] for i in range(3): for j in range(3): for k in range(3): res[i][k] += X[i][j] * Y[j][k] for i in range(3): for j in range(3): res[i][j] %= b return res def det(a): res = 0 for j in range(3): v = 1 for i in range(3): v *= a[i][(j+i) % 3] res += v for j in range(3): v = 1 for i in range(3): v *= a[i][(j-i) % 3] res -= v return res an = [[int(i == j) for j in range(3)] for i in range(3)] for k in range(n.bit_length())[::-1]: an = mul(an, an) if n >> k & 1: an = mul(an, a) print(det(an) % b)