首先有一个很好玩的线性递推求逆元的方法:
http://blog.youkuaiyun.com/whyorwhnt/article/details/19169035
对于这道题,若设gcd(a,b)=1,则必然有gcd(a+kb,b)=1,因在mod b系中,加b对于余数无影响。
下面需要对此题证明一个结论,即:在1~n!中有
phi(m!)n!m!
个数与m!互质。
首先phi即在m!范围内与m!互质的数,然后把它扩展到n!范围内,即为答案。
Ans=phi(m!)n!m!=(∏p|np−1p)n!
由于所有运算都是O(n)的,于是预处理O(n),查询O(1)
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000005;
int T,mod,n,m,cnt;
int prime[maxn],rev[maxn],fac[maxn],deno[maxn];
bool not_prime[maxn];
void linear_shaker()
{
for(int i=2;i<maxn;i++)
{
if(!not_prime[i])
prime[++cnt]=i;
int t;
for(int j=1;j<=cnt&&(t=prime[j]*i)<maxn;j++)
{
not_prime[t]=true;
if(i%prime[j]==0)break;
}
}
rev[1]=1;
for(int i=2;i<maxn;i++)
rev[i]=1LL*(mod-mod/i)*rev[mod%i]%mod;
fac[1]=1;
for(int i=2;i<maxn;i++)
fac[i]=1LL*fac[i-1]*i%mod;
deno[1]=1;
for(int i=2;i<maxn;i++)
if(!not_prime[i])deno[i]=1LL*deno[i-1]*(i-1)%mod*rev[i]%mod;
else deno[i]=deno[i-1];
}
int main()
{
scanf("%d%d",&T,&mod);
linear_shaker();
while(T--)
{
scanf("%d%d",&n,&m);
printf("%d\n",1LL*fac[n]*deno[m]%mod);
}
}