Light OJ 1067 Combinations
来源:互联网 发布:拜尔电动牙刷自慰知乎 编辑:程序博客网 时间:2024/05/18 10:26
Description
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).
Output
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
题意:求C(n,m)%mod;
由于数据较大,不能直接求解,采用逆元;
先看逆元:
乘法逆元
定义:
满足a*k≡A (mod p)的k值就是a关于p的乘法逆元。
为什么要有乘法逆元呢?
当我们要求(a/b) mod p的值,且a很大,无法直接求得a/b的值时,我们就要用到乘法逆元。
我们可以通过求b关于p的乘法逆元k,将a乘上k再模p,即(a*k) mod p。其结果与(a/b) mod p等价。
证:
根据b*k≡1 (mod p)有b*k=p*x+1。
k=(p*x+1)/b。
把k代入(a*k) mod p,得:
(a*(p*x+1)/b) mod p
=((a*p*x)/b+a/b) mod p
=[((a*p*x)/b) mod p +(a/b)] mod p
=[(p*(a*x)/b) mod p +(a/b)] mod p //p*[(a*x)/b] mod p=0
所以原式等于:(a/b) mod p
对于这道题,要求n%mod的逆元,直接费马小定理,n'=n^(mod-2)%mod,所以可以用快速幂求。满足a*k≡A (mod p)的k值就是a关于p的乘法逆元。
为什么要有乘法逆元呢?
当我们要求(a/b) mod p的值,且a很大,无法直接求得a/b的值时,我们就要用到乘法逆元。
我们可以通过求b关于p的乘法逆元k,将a乘上k再模p,即(a*k) mod p。其结果与(a/b) mod p等价。
证:
根据b*k≡1 (mod p)有b*k=p*x+1。
k=(p*x+1)/b。
把k代入(a*k) mod p,得:
(a*(p*x+1)/b) mod p
=((a*p*x)/b+a/b) mod p
=[((a*p*x)/b) mod p +(a/b)] mod p
=[(p*(a*x)/b) mod p +(a/b)] mod p //p*[(a*x)/b] mod p=0
所以原式等于:(a/b) mod p
#include <iostream>#include <cstdio>using namespace std;#define LL long long#define mod 1000003LL com[1000009];LL cob[1000009];LL pow(LL a,LL b){ LL ans=1; while(b) { if(b%2==1) { ans=(ans*a)%mod; } a=(a*a)%mod; b/=2; } return ans;}int main(){ int t,cas=1; int m,k; com[0]=cob[0]=1; for(int i=1;i<=1000005;i++) { com[i]=(com[i-1]*i)%mod; cob[i]=pow(com[i],mod-2); } scanf("%d",&t); while(t--) { scanf("%d%d",&m,&k); LL ans=com[m]*cob[k]%mod*cob[m-k]%mod; printf("Case %d: %lld\n",cas++,ans); } return 0;}
0 0
- Light OJ 1067 Combinations
- LIght oj 1067 Combinations
- light oj 1067Combinations
- Light OJ 1067 Combinations(逆元)
- light oj 1067 Combinations (组合数的lucas定理)
- Light OJ 1067 Combinations (费小马定理求逆元)
- Light OJ 1067 Combinations (乘法逆元)
- LIGHT OJ-1067 Combinations【逆元(欧拉)+快速幂+同余】
- light oj 1067 组合数取模
- light oj
- light oj
- Light OJ
- Light OJ
- 【LeetCode OJ】Combinations
- LeetCode OJ:Combinations
- LeetCode OJ - Combinations
- LeetCode OJ Combinations
- <LeetCode OJ> 77. Combinations
- Exception in thread "main" java.lang.NoClassDefFoundError:
- Java-内部类
- POJ 3077 Rounders(高精度)
- Java学习--疯狂Java讲义--1
- 给jekyll添加炫酷简洁的搜索
- Light OJ 1067 Combinations
- Oracle中出现了空值要与数字相加问题 怎么解决
- C++箴言:理解 typename 的两个含义
- HDU 4871 Shortest-path tree (最短路+树上点分治)
- 推荐几个非常有用的开发工具之Android Studio插件
- xshell的快捷键(提高效率)
- merge into在Oracle中怎么使用
- ubuntu 下cmake、QT、geany的安装
- nim和面向对象(二)