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以内所有的素数。
除法直接乘上一个逆元,用拓展欧几里得算法求一下。
【代码】
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; }
相关文章推荐
- web Filter中使用spring注入的bean
- 阿里2016春招实习生内推面试
- android环境搭建
- Glide转化圆形图片的坑
- QT编写DLL给外部程序调用,提供VC/C#/C调用示例(含事件)
- cypher一(语法)
- 在Ubuntu中,使用minicom抓串口log
- java web监听器配置
- 安卓文本样式-Spannable的使用
- 手机UC浏览器字体放大
- NSArray, NSSet, NSDictionary
- HDU5461 沈阳网络赛题
- javaweb学习总结(十八)——JSP属性范围
- Marlin固件的步进电机控制代码解析
- java反射创建工厂对象
- Socket通信原理和实践
- Bzoj2190:[SDOI2008]仪仗队:欧拉函数
- 第五周项目1.2-三角形类雏形(改善)
- iOS磨砂(半透明)效果实现
- 架构演化中的软件设计原则