现在的位置: 首页 > 综合 > 正文

【bzoj 2186】: [Sdoi2008]沙拉公主的困惑

2017年04月28日 ⁄ 综合 ⁄ 共 2077字 ⁄ 字号 评论关闭

http://www.lydsy.com/JudgeOnline/problem.php?id=2186

紧跟zky 3月份的步伐~~~~~~~~~~~~~~~~~

1~n!与m!互质的数的个数(m<=n) 
分为两部分: 
1.1~m!
2.m!+1~n!
Ans=phi[m!]*n!/m!
   =m!*((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)*n!/m!
   =((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)*n!

预处理
1.n!
2.((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)

//#define _TEST _TEST
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <bitset>
using namespace std;
/************************************************
Code By willinglive    Blog:http://willinglive.cf
************************************************/
/////////////////////////////////////////////////
#define rep(i,l,r) for(int i=l,___t=(r);i<=___t;i++)
#define per(i,r,l) for(int i=r,___t=(l);i>=___t;i--)
#define MS(arr,x) memset(arr,x,sizeof(arr))
#define LL long long
#define INE(i,u,e) for(int i=head[u];~i;i=e[i].next)
inline const LL getint()
{
    LL r=0,k=1;char c=getchar();
    for(;c<'0'||c>'9';c=getchar())if(c=='-')k=-1;
    for(;c>='0'&&c<='9';c=getchar())r=r*10+c-'0';
    return k*r;
}
/////////////////////////////////////////////////
const LL N=10000000;
/*
1~n!与m!互质的数的个数(m<=n) 
分为两部分: 
1.1~m!
2.m!+1~n!
Ans=phi[m!]*n!/m!
   =m!*((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)*n!/m!
   =((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)*n!
预处理
1.n!
2.((p1-1)/p1*(p2-1)/p2*...*(pk-1)/pk)
*/
LL mod;
int q;
LL n,m;

LL fac[N+10];
LL inv[N+10];
LL prim[670000],cnt;
//bitset<N+10>flag;
bool flag[N+10];
LL pre[N+10];
/////////////////////////////////////////////////

/////////////////////////////////////////////////
void input()
{
    cin>>q>>mod;
}
void solve()
{
	// 1 fac[]
	fac[0]=1;
	rep(i,1,N) fac[i]=(i*fac[i-1])%mod;
	// 2 inv[]
    inv[1]=1;
    rep(i,2,min(N,mod))
    	inv[i]=(mod-mod/i)*inv[mod%i]%mod;
	// 3 prim[]
	rep(i,2,N)
	{
		if(!flag[i]) prim[++cnt]=i;
		for(int j=1;j<=cnt && i*prim[j]<=N;j++)
		{
			flag[i*prim[j]]=1;
			if(i%prim[j]==0)break;
		}
	}
	//cout<<cnt<<endl;
	// 4 pre[]
	pre[1]=1;
	rep(i,2,N)
	{
		pre[i]=pre[i-1];
		if(!flag[i])
		{
			pre[i]=(pre[i]*(((i-1)*inv[i%mod])%mod))%mod;
		}
	}
	// 5 query
    while(q--)
    {
    	n=getint(); m=getint();
        printf("%lld\n",(pre[m]*fac[n])%mod);
    }
}
/////////////////////////////////////////////////
int main()
{
    #ifndef _TEST
    freopen("std.in","r",stdin); freopen("std.out","w",stdout);
    #endif
    input();
    solve();
    return 0;
}

抱歉!评论已关闭.