Modulo the combination number

Source: Internet
Author: User

Before you look at this, we suggest you take a look at n! ......

for the number of combinations we can represent them as factorial forms : C (n,k) = . Then we might as well put these three factorial in the form of a previous topic. In this case, if the e1>e2+e3 can be divisible by p ,e1=e2+e3 cannot be p divisible. C (n,k) =a1 (a2a3)-1 in case of an inability to be divisible

1 intMod_comb (intNintKintp) {2     if(n<0|| k<0|| N&LT;K)return 0;3     intA1=mod_fact (N,P,E1), A2=mod_fact (K,p,e2), A3=mod_fact (nk,p,e3);4     if(E1&GT;E2+E3)return 0;5     returnA1*mod_inverse (a2*a3%p, p)%p;6}
View Code

In addition, we can also use Lucas to beg.

Lucas theorem: We make n=sp+q, M=tp+r (q,r≤p) have

The concrete proof is as follows:

Let's first prove a simple formula:

C (P, f)%p= p!/(f! ( P-F)! %p because P is a prime number, and F and (P-F) on the denominator are smaller than p, that is, there are no numbers in the denominator that can take p, so%p must be equal to 0. Similarly, with a little expansion, we can get C (n,f)%p=0 (n>=p). (In fact, there is no egg for the proof of Lucas theorem)

By proving the formula, we can begin to prove Lucas ' theorem.

for (1+x) sp+q≡ (1+x) SPX (1+X) Q≡ ((1+X) p) SX (1+X) Q≡ (based on the two-polynomial theorem, and then in the formula above, so we can get) (1+XP) SX (1+X) Q≡ (again according to the two-item theorem) ≡ (mod p)

In the end we can get

Let's calculate the coefficients of xtp+r on the left and right sides:

Left =c (sp+q, tp+r), right =c (S, t) XC (q, R)

Because left = right, so we finally got Lucas theorem.

With Lucas ' theorem, we have this code, and this code is really good at understanding

1 intLucas (intNintMintp) {2     Long Longans=1;3      while(n&&m&&ans) {4Ans*=comb (n%p,m%p,p)%p;//Comb () to find the number of combinations5N/=p;m/=p;6     }7     returnans;8}
View Code

Modulo the combination number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.