Lucac find the number of combinations (combinations FZU - 2020)

Lucas theorem is used to find C (n, m) mod p, p is a prime number value. (Note: p must be a prime number)
 
Gives the number of combinations of C (n, m), m represents a selected number of program elements from the n elements. For example C (5,2) = 10, C (4,2) = 6. But when n, m when larger, C (n, m) great! So you want xiaobo output C (n, m) mod value of p!

Input

The first data input line T is a positive integer, the number (T <= 100) indicating that the following data set is a data group T, each data has three positive integers n, m, p (1 <= m <= n < = 10 ^ 9, m <= 10 ^ 4, m <p <10 ^ 9, p is a prime)

Output

For each test, it outputs a positive integer representing the C (n, m) mod p the result.

Sample Input

2
5 2 3
5 2 61

Sample Output

1
10
#include <cstdio>
#define ll long long

using namespace std;

ll mulit(ll a,ll b,ll m)
{
    ll ans=0;
    while(b)
    {
        if(b&1)
        {
            ans=(ans+a)%m;
        }
        a=(a<<1)%m;
        b>>=1;
    }
    return ans;
}

ll quick_mod(ll a,ll b,ll m)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
        {
            ans=mulit(ans,a,m);
        }
        a=mulit(a,a,m);
        b>>=1;
    }
    return ans;
}

ll comp(ll a,ll b,ll m)
{
    if(a<b)
    {
        return 0;
    }
    if(a==b)
    {
        return 1;
    }
    if(b>a-b)
    {
        b=a-b;
    }
    ll ans=1,ca=1,cb=1;
    for(int i=0;i<b;i++)
    {
        ca=ca*(a-i)%m;
        cb=cb*(b-i)%m;
    }
    ans=ca*quick_mod(cb,m-2,m)%m;
    return ans;
}

ll lucas(ll a,ll b,ll m)
{
    ll ans=1;
    while(a&&b)
    {
        ans=(ans*comp(a%m,b%m,m))%m;
        a/=m;
        b/=m;
    }
    return ans;
}

int main()
{
    int T;
    ll n,m,p;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld %lld %lld",&n,&m,&p);
        ll ans=lucas(n,m,p);
        printf("%lld\n",ans);
    }
    return 0;
}

template 

A, B are non-negative integers, p is a prime number. AB p hex written: A = a [n] a [n-1] ... a [0], B = b [n] b [n-1] ... b [0].
Number of combinations C (A, B) and C ([n] a, b [n]) * C (a [n-1], b [n-1]) * ... * C (a [0] , b [0]) modp congruence

即:Lucas(n,m,p)=c(n%p,m%p)*Lucas(n/p,m/p,p) 

To solve for n! P%, for example, the n segments, each of the p section, each section is the same as a result of seeking. But need to be addressed separately at the end of each segment p, 2p, ..., p to extract, you will find just the remaining number is (n / p) !, became the equivalent of a child under the question, so recursive solution It can be.

Guess you like

Origin www.cnblogs.com/pzh2019/p/11354839.html