组合数取模(逆元+快速幂)
来源:互联网 发布:python下怎样安装mysql 编辑:程序博客网 时间:2024/06/10 08:37
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
LightOJ 1067
Given n different objects, you want to take k of them. How many ways to can do it?
For example, say there are 4 items; you want to take 2 of them. So, you can do it 6 ways.
Take 1, 2
Take 1, 3
Take 1, 4
Take 2, 3
Take 2, 4
Take 3, 4
Input
Input starts with an integer T (≤ 2000), denoting the number of test cases.
Each test case contains two integers n (1 ≤ n ≤ 106), k (0 ≤ k ≤ n).
For each case, output the case number and the desired value. Since the result can be very large, you have to print the result modulo 1000003.
Sample Input
3
4 2
5 0
6 4
Sample Output
Case 1: 6
Case 2: 1
Case 3: 15
除法求模不能类似乘法,对于(A/B)mod C,直接(A mod C)/ (B mod C)是错误的;找到B的逆元b(b=B^-1);求出(A*b)modC即可;
由费马小定理:B 关于 P 的逆元为 B^(p-2);
费马小定理(Fermat Theory)是数论中的一个重要定理,其内容为: 假如p是质数,且gcd(a,p)=1,那么 a(p-1)≡1(mod p)。即:假如a是整数,p是质数,且a,p互质(即两者只有一个公约数1),那么a的(p-1)次方除以p的余数恒等于1。所以,a^-1*a=1=a^(p-1),所以:a^-1=a^(p-2);
数学排列组合公式:C(n,m)= n!/(m!*(n-m)!)
代码:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define LL long long #define G 1100000 #define mod 1000003 LL pri[G]; LL ni[G],ans; LL pow(LL a,int b) { LL ans=1,base=a; while (b>0) { if (b%2==1) ans=(base*ans)%mod; base=(base*base)%mod; b/=2; } return ans; } void s() //打表 { pri[0]=1; ni[0]=1; for (int i=1;i<G ;i++) { pri[i]=pri[i-1]*i%mod; //N! ni[i]=pow(pri[i],mod-2); } } int main() { s(); int t,n,b,k=1;scanf("%d",&t); while (t--) { scanf("%d%d",&n,&b); ans=((pri[n]*ni[b]%mod)*ni[n-b])%mod; // C(n,m)= n!/(m!*(n-m)!) printf("Case %d: %lld\n",k++,ans); } return 0; }
0 0
- 组合数取模(逆元+快速幂)
- zoj3903-数学公式(快速幂除法逆元组合数模板)
- HDU 3037 Saving Beans (组合+Lucas定理+逆元+快速幂)
- CodeForces 300C Beautiful Numbers(乘法逆元/费马小定理+组合数公式+快速幂)
- HDU 5894 hannnnah_j’s Biological Test (组合数学 + 快速幂 + 乘法逆元)
- UVALive 7040 Color (容斥定理 + 递推求逆元 + 组合数 + 快速幂)
- 51 nod 加号分配 组合数学(逆元,快速幂)
- 【板子】gcd、exgcd、乘法逆元、快速幂、快速乘、筛素数、快速求逆元、组合数
- 【板子】gcd、exgcd、乘法逆元、快速幂、快速乘、筛素数、快速求逆元、组合数
- hdu4675——GCD of Sequence(莫比乌斯反演+组合数取模+乘法逆元+快速幂)
- 【快速幂+组合数+逆元】HDU5698瞬间移动【2016"百度之星" - 初赛(Astar Round2B)】
- 51nod 1119 机器人走方格V2(求组合数,费马小定理+快速幂/逆元+gcd)
- 组合数取模之逆元
- 快速幂 + 逆元
- 【容斥原理+逆元+组合数+费马小定理+快速幂】UVALive
- bzoj 1965(快速幂+逆元)
- 等比数列求和 (快速幂 + 逆元)
- Codeforces 521C 组合数取模(乘法逆元)
- opencv,已知一个图像的轮廓,取出图像轮廓里的图//C++
- Eclipse和Studio去除头部标题
- 学习笔记(三)——大名鼎鼎的Fragement
- 深度学习caffe的代码怎么读?
- JAVA中局部内部类和匿名内部类的特点和作用?
- 组合数取模(逆元+快速幂)
- C#入门7.6——查找数组元素
- 实习面试时被问到的数据库基础知识
- 封装两个简单的jquery组件
- 字符串中字母替换-E
- leetcode 197. Rising Temperature
- iOS判断应用是否获取到系统相机 相册的授权 以及如何请求授权
- mina2多端口配置实现
- js判断字符串中是否包含汉字