#define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) #if defined(_MSC_VER) || __cplusplus > 199711L #define aut(r,v) auto r = (v) #else #define aut(r,v) typeof(v) r = (v) #endif #define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it) #define all(o) (o).begin(), (o).end() #define pb(x) push_back(x) #define mp(x,y) make_pair((x),(y)) #define mset(m,v) memset(m,v,sizeof(m)) #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3fLL using namespace std; typedef vector vi; typedef pair pii; typedef vector > vpii; typedef long long ll; typedef vector vl; typedef pair pll; typedef vector > vpll; typedef vector vs; typedef long double ld; template inline void amin(T &x, U y) { if(y < x) x = y; } template inline void amax(T &x, U y) { if(x < y) x = y; } struct GModInt { static int Mod; int x; GModInt(): x(0) { } GModInt(signed sig) { if((x = sig % Mod + Mod) >= Mod) x -= Mod; } GModInt(signed long long sig) { if((x = sig % Mod + Mod) >= Mod) x -= Mod; } int get() const { return x; } GModInt &operator+=(GModInt that) { if((x += that.x) >= Mod) x -= Mod; return *this; } GModInt &operator-=(GModInt that) { if((x += Mod - that.x) >= Mod) x -= Mod; return *this; } GModInt &operator*=(GModInt that) { x = (unsigned long long)x * that.x % Mod; return *this; } GModInt &operator/=(GModInt that) { return *this *= that.inverse(); } GModInt operator+(GModInt that) const { return GModInt(*this) += that; } GModInt operator-(GModInt that) const { return GModInt(*this) -= that; } GModInt operator*(GModInt that) const { return GModInt(*this) *= that; } GModInt operator/(GModInt that) const { return GModInt(*this) /= that; } //Modが素数であるとか確認すること! GModInt inverse() const { long long a = x, b = Mod, u = 1, v = 0; while(b) { long long t = a / b; a -= t * b; std::swap(a, b); u -= t * v; std::swap(u, v); } return GModInt(u); } GModInt operator-() const { GModInt t; t.x = x == 0 ? 0 : Mod - x; return t; } }; int GModInt::Mod = 0; typedef GModInt mint; int main() { const int MaxT = 100, K = 100000, MaxNM = 1000000000; int T; scanf("%d", &T); if(!(1 <= T && T <= MaxT)) { cerr << "err" << endl; return 1; } rep(ii, T) { int N, M; scanf("%d%d", &N, &M); if(!(1 <= M && M <= MaxNM && max(0, M - K) <= N && N <= MaxNM)) { cerr << "err" << endl; return 1; } mint::Mod = M; mint ans; if(M <= N) { ans = 0; }else if(M <= 2 * K) { //N < M <= 2K ans = 1; rer(i, 1, N) ans *= i; }else { //2K < M, M - K <= N より、 //K < M/2 で、M - M/2 < M - K で、 //M - M/2 < N となり、M/2 < N。 bool isPrime = true; for(int i = 2; i*i <= M; ++ i) isPrime &= M % i != 0; if(!isPrime) { ans = 0; }else { mint prod = 1; rer(i, N+1, M-1) prod *= i; ans = -prod.inverse(); } } printf("%d\n", ans.get()); } return 0; }