#include using namespace std; long long MOD; vector> matmul(vector> A, vector> B){ vector> C(4, vector(4, 0)); for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ for (int k = 0; k < 4; k++){ C[i][k] += A[i][j] * B[j][k]; C[i][k] %= MOD; } } } return C; } vector> matpow(vector> A, long long N){ vector> ans(4, vector(4, 0)); for (int i = 0; i < 4; i++){ ans[i][i] = 1 % MOD; } while (N > 0){ if (N % 2 == 1){ ans = matmul(ans, A); } A = matmul(A, A); N /= 2; } return ans; } vector> solve(vector> A, long long N){ vector> A2(4, vector(4, 0)); for (int i = 0; i < 2; i++){ for (int j = 0; j < 2; j++){ A2[i][j] = (A[i][j] % MOD + MOD) % MOD; } } for (int i = 0; i < 2; i++){ A2[i + 2][i] = 1 % MOD; A2[i + 2][i + 2] = 1 % MOD; } A2 = matpow(A2, N); vector> A3(2, vector(2)); for (int i = 0; i < 2; i++){ for (int j = 0; j < 2; j++){ A3[i][j] = A2[i + 2][j]; } } for (int i = 0; i < 2; i++){ A3[i][i] += (MOD - 1) % MOD; A3[i][i] %= MOD; } return A3; } bool check_odd(vector> A){ long long tr = A[0][0] + A[1][1]; long long det = A[0][0] * A[1][1] - A[0][1] * A[1][0]; return 1 - tr + det < 0; } bool check_even(vector> A){ long long tr = A[0][0] + A[1][1]; long long det = A[0][0] * A[1][1] - A[0][1] * A[1][0]; return (1 - tr + det < 0) ^ (1 + tr + det < 0); } int main(){ int T; cin >> T; for (int i = 0; i < T; i++){ long long N, B; cin >> N >> B; MOD = B; vector> A(2, vector(2)); for (int j = 0; j < 2; j++){ for (int k = 0; k < 2; k++){ cin >> A[j][k]; } } long long tr = A[0][0] + A[1][1]; long long det = A[0][0] * A[1][1] - A[0][1] * A[1][0]; vector> E(2, vector(2, 0)); for (int j = 0; j < 2; j++){ E[j][j] = 1; } if (A == E){ cout << (N % B) * (N % B) % B << endl; } else { vector> S = solve(A, N + 1); long long ans = S[0][0] * S[1][1] - S[0][1] * S[1][0]; ans = (ans % MOD + MOD) % MOD; if (ans == 0){ cout << ans << endl; } else { bool ok = true; ok ^= check_odd(A); if (N % 2 == 0){ ok ^= check_even(A); } else { ok ^= check_odd(A); } if (det < 0){ ok = !ok; } if (!ok){ ans = (MOD - ans) % MOD; } cout << ans << endl; } } } }