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*b=1(mod n),那么b就是a关于模n的乘法逆元,此时,也可称作a与b互为乘法逆元。
思路:1.C(n,m)%mod=n!/m!*(n-m)!%mod除以一个数并取模等价于乘以这个数的逆元然后再去模.可将n!/m!*(n-m)!%mod等价于n!/m!%mod*1/(n-m)!%mod.再等价于n!*inv[m!]%mod(m!的逆元)*inv[(n-m)!]((n-m!)的逆元).
2.也就是说,求出逆元即可求解。c*x=1(mod n)=1-k*n等价于c*x+k*n=1所以可以用扩展欧几里得算法求得x(逆元)的值。为了保证x是正整数,通常需要加上:x=(x%n+n)%n.
#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define m 1000003
long long f[];
long long inv[];
long long x,y,gcd;
void extend_gcd(long long a, long long b)
{
if(b == )
{
x = ;
y = ;
gcd = a;
}
else {
extend_gcd(b, a%b);
long long temp = x;
x = y;
y = temp - a/b*y;
}
}
void factorial()
{
f[]=;inv[]=;
for(int i=;i<=;i++)
{
f[i]=f[i-]*i%m;
extend_gcd(f[i],m);
inv[i]=(x%m+m)%m;
}
}
int main()
{
factorial();
int t;
int cnt=;
scanf("%d\n",&t);
int a1,b1;
while(t--)
{
scanf("%d%d",&a1,&b1);
long long ans=f[a1]*inv[b1]%m*inv[a1-b1]%m;
printf("Case %d: %lld\n",++cnt,ans); } return ;
}
//3
//
//4 2
//
//5 0
//
//6 4 //3
//1 1
//2 3
//4 3