import java.io.*;
import java.util.*;
public class Main {
static int m=0;
InputReader in
= new InputReader
(System.
in); int t = in.nextInt();
for(int z=0;z<t;z++){
long n = in.nextLong();
m = in.nextInt();
long a = in.nextLong();
long b = in.nextLong();
long c = in.nextLong();
if(n>=m){
pw.println("0");
}
else{
long ans = 1;
for(int i=1;i<=(int)n;i++){
ans*=power(i, i);
ans%=m;
}
pw.println(ans);
}
}
pw.close();
}
private static long power(int x, int y) {
long temp;
if( y == 0)
return 1;
temp = power(x, y/2)%m;
if (y%2 == 0)
return ((temp%m)*(temp%m))%m;
else
return ((x%m)*((temp%m)*(temp%m))%m)%m;
}
static class InputReader {
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private SpaceCharFilter filter;
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}