您的位置:首页 > 其它

bzoj 2186 [Sdoi2008]沙拉公主的困惑(欧拉函数,逆元)

2016-03-30 15:10 369 查看
【题目链接】

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

【题意】

若干个询问,求1..n!中与m!互质的个数。

【思路】

首先有gcd(a,b)=gcd(a+b,b),则一个与m!互素的数+m!依旧与m!互素,每m!个看作一组,则1..m!中有phi(m!)*(n!/m!)的数与m!互素。即求:

n!(1-1/p1)(1-1/p2)(1-1/p3)… mod R

=n!(1-p1)(1-p2)(1-p3)…/(p1*p2*p3…) mod R

其中p1…为m!的质因子即m以内所有的素数。

除法直接乘上一个逆元,用拓展欧几里得算法求一下。

【代码】

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

typedef long long ll;
const int N = 1e7+3;

int fac
,su
,ans
,tot;
int n,m,R,T,vis
;

int gcd(int a,int b,int& d,int& x,int& y)
{
if(!b) { d=a; x=1; y=0; }
else { gcd(b,a%b,d,y,x); y-=x*(a/b); }
}
int inv(int a,int n)
{
int d,x,y;
gcd(a,n,d,x,y);
return d==1? (x+n)%n:-1;
}

void get_pre()
{
fac[1]=1;
for(int i=2;i<N;i++) fac[i]=(ll)fac[i-1]*i%R;
for(int i=2;i<N;i++) {                                            //快速线性筛法求素数
if(!vis[i]) su[++tot]=i;
for(int j=1;su[j]*i<N&&j<=tot;j++) {
vis[i*su[j]]=1;
if(i%su[j]==0) break;
}
}
ans[1]=1;
for(int i=2;i<N;i++) {
ans[i]=ans[i-1];
if(!vis[i]) ans[i]=(ll)ans[i]*(i-1)%R*inv(i,R)%R;
}
}

int main()
{
scanf("%d%d",&T,&R);
get_pre();
while(T--) {
scanf("%d%d",&n,&m);
printf("%lld\n",(ll)fac
*ans[m]%R);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: