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,所以可以用快速幂求。

#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
原创粉丝点击