[To] combination number modulus Lucas theorem

Source: Internet
Author: User
Tags modulus

For C (n, m) mod p. Here the N,m,p (P is the prime number) are very large cases. The formula for C (n, m) = C (n-1,m) + C (n-1, m-1) can no longer be recursive.

The Lusac theorem is used here.

For non-negative integers m and N and a prime p, the following congruence relation holds:

where

and

is the base p expansions of m and n respectively.

For a separate C (NI, MI) mod p, the known C (n, m) mod p = n!/(m! ( N-M)!) MoD p. Obviously, the division takes the mold, and here we use the m!. (n-m)! The inverse of the element.

According to Fermat theorem:

Known (A, p) = 1, then ap-1≡1 (mod p), so a*ap-2≡1 (mod p).

i.e. (m! ( N-M)!) The inverse is (m! ( N-M)!) P-2;

Code:

#include <iostream>
using namespace Std;
typedef long Long LL;

ll Exp_mod (ll A, ll B, ll P) {    ll res = 1;    while (b! = 0) {        if (b&1) res = (res * a)% P;        A = (a*a)% p;        b >>= 1;    }    return res;} ll Comb (ll A, ll B, ll p) {    if (a < b)   return 0;    if (a = = b)  return 1;    if (b > a)   b = a A;    LL ans = 1, CA = 1, cb = 1;    for (LL i = 0; i < b; ++i) {        CA = (CA * (a-i))%p;        CB = (CB * (b-i))%p;    }    Ans = (Ca*exp_mod (CB, P-2, p))% P;    return ans;} ll Lucas (int n, int m, int p) {     ll ans = 1;     while (N&&m&&ans) {        ans = (Ans*comb (n%p, m%p, p))% P;        n/= p;        M/= p;     }     return ans;} int main () {    Read ();    int n, m, p;    while (~SCANF ("%d%d%d", &n, &m, &p)) {        printf ("%lld\n", Lucas (N, M, p));    }    return 0;}

[To] combination number modulus Lucas theorem

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.