题目:https://vjudge.net/contest/242287#problem/A
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
利用扩展欧几里得和费马小定理求乘法逆元。需要给分母求乘法逆元,将出发变成乘逆元得乘法。
扩展欧几里得
#include <iostream>
#include <stdio.h>
#include <string.h>
#define LL long long
#define MAXN 1000005
#define mod 1000003
using namespace std;
LL com[MAXN];
void C()
{
com[1]=com[0]=1;
for(LL i=2;i<MAXN;i++)
com[i]=(i*com[i-1])%mod;
}
LL exgcd(LL a, LL b, LL &x, LL &y) {
if(b == 0) {
x = 1;
y = 0;
return a;
}
else {
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
}
LL inv(LL a, LL p) {
LL x, k;
LL d = exgcd(a, p, x, k);
if(d == 1) return (x % p + p) % p;
else return -1;
}
int main()
{
C();
int t;
int Case=0;
scanf("%d",&t);
while(t--)
{
int n,k;
scanf("%d%d",&n,&k);
//cout<<com[k]<<endl;
LL a=com[n];
if(k*2>n)
k=n-k;
LL b=inv(com[k], mod);
LL c=inv(com[n-k],mod);
// cout<<c<<endl;
LL ans=(a*b*c)%mod;
printf("Case %d: %lld\n",++Case,ans);
}
return 0;
}
费马小定理:
#include <iostream>
#include <stdio.h>
#include <string.h>
#define LL long long
#define MAXN 1000005
#define mod 1000003
using namespace std;
LL com[MAXN];
void C()
{
com[1]=com[0]=1;
for(LL i=2;i<MAXN;i++)
com[i]=(i*com[i-1])%mod;
}
LL pow_mod(LL a, LL n, LL p){
LL ret = 1;
LL tmp = a;
while(n) {
if(n & 1) ret = (ret * tmp) % p;
tmp = tmp * tmp % p;
n >>= 1;
}
return ret;
}
LL inv(LL a, LL p) {
return pow_mod(a, p-2, p);
}
int main()
{
C()
int t;
int Case=0;
scanf("%d",&t);
while(t--)
{
int n,k;
scanf("%d%d",&n,&k);
//cout<<com[k]<<endl;
LL a=com[n];
if(k*2>n)//组合数对称性
k=n-k;
LL b=inv(com[k], mod);
LL c=inv(com[n-k],mod);
//cout<<c<<endl;
LL ans=(a*b*c)%mod;
printf("Case %d: %lld\n",++Case,ans);
}
return 0;
}