C(n,m)%p定理

数论Lucas定理是用来求 c(n,m) mod p的值,p是素数(从n取m组合,模上p)。
描述为:
Lucas(n,m,p)=cm(n%p,m%p)* Lucas(n/p,m/p,p)
Lucas(x,0,p)=1;
cm(a,b)=a! * (b!*(a-b)!)^(p-2) mod p
也= (a!/(a-b)!) * (b!)^(p-2)) mod p
这里,其实就是直接求 (a!/(a-b)!) / (b!) mod p
由于 (a/b) mod p = a * b^(p-2) mod p
 
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <string>
 7 #include <vector>
 8 #include <stack>
 9 #include <queue>
10 #include <set>
11 #include <map>
12 #include <list>
13 #include <iomanip>
14 #include <cstdlib>
15 #include <sstream>
16 using namespace std;
17 typedef long long LL;
18 const int INF=0x5fffffff;
19 const double EXP=1e-6;
20 const int MS=801;
21 const int mod=1000000007;
22 
23 LL power(LL a,LL b)
24 {
25     LL ans;
26     for(ans=1;b;b>>=1,a=a*a%mod)
27         if(b&1)
28             ans=ans*a%mod;
29     return ans;
30 }
31 
32 LL get(LL n,LL m)
33 {
34     if(n<m)
35         return 0;
36     if(m>n-m)
37         m=n-m;
38     LL s1=1,s2=1;
39     for(LL i=0;i<m;i++)
40     {
41         s1=s1*(n-i)%mod;
42         s2=s2*(i+1)%mod;
43     }
44     return s1*power(s2,mod-2)%mod;
45 }
46 
47 LL lucas(LL n,LL m)
48 {
49     if(m==0)
50         return 1;
51     return get(n%mod,m%mod)*lucas(n/mod,m/mod);
52 }
53 
54 int main()
55 {
56     cout<<lucas(1000LL,500LL)<<endl;
57     return 0;
58 }

 

posted @ 2015-03-23 19:27  daydaycode  阅读(620)  评论(0编辑  收藏  举报