1. 程式人生 > >Lucas定理求組合數模板

Lucas定理求組合數模板

end code == turn tdi div rac bsp 模板

$Lucas(n,m,p)=C(n\%p,m\%p)*Lucas(n/p,m/p,p)$

$C^n_m=\frac{n!}{m!(n-m)!}$

$x^{p-1}\equiv 1(mod p)\Longrightarrow x*x^{p-2}\equiv 1(mod p)\Longrightarrow x^{p-2}\equiv (1/x)^p(mod p)$

$C^n_m=n!*[m!(n-m)!]^{p-2}(mod p)$

 1 #include <iostream>
 2 #include <cstdio>
 3 #define ll long long
 4 using
namespace std; 5 ll n,m,p,fac[100001]; 6 ll power(ll a,ll b,ll p) 7 { 8 ll t=a%p,s=1; 9 while(b) 10 { 11 if (b%2==1) s=s*t%p; 12 t=t*t%p; 13 b/=2; 14 } 15 return s; 16 } 17 ll C(ll n,ll m,ll p) 18 { 19 if (m>n) return 0; 20 return fac[n]*power(fac[m]*fac[n-m],p-2
,p)%p; 21 } 22 ll Lucas(ll n,ll m,ll p) 23 { 24 if (m==0) return 1; 25 return C(n%p,m%p,p)*Lucas(n/p,m/p,p)%p; 26 } 27 int main() 28 { 29 cin>>n>>m>>p; 30 fac[0]=1; 31 for (ll i=1;i<=p;i++) fac[i]=fac[i-1]*i%p; 32 cout<<Lucas(n,m,p)<<endl; 33 }

Lucas定理求組合數模板