卢卡斯定理(模板)

卢卡斯定理

卢卡斯定理主要用来求大数组合数。
模板题:https://www.luogu.org/problem/P3807

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <algorithm>
#include <stack>
#include <vector>
#include <set>
#include <iostream>
#include <queue>
#include <string>
#include <math.h>
typedef long long LL;
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
#define mid(l,r) (( l + r ) / 2)
#define lowbit(x) (( x & ( - x )))
#define lc(root) ((root * 2))
#define rc(root) ((root * 2 + 1))
#define me(array,x) (memset( array , x , sizeof( array ) ) )
const int maxn = 200004;

LL POW(LL a,LL b,int p)
{
    LL ans = 1;
    while(b){
        if(b&1)
            ans = (ans%p*a%p) % p;
        a = (a%p*a%p) % p;
        b >>= 1;
    }
    return ans%p;
}

LL C(int n,int m,int p)
{
    if(m > n)return 0;
    if(m == n)return 1;
    if(m > n - m)m = n - m;
    LL a = 1, b = 1 ;
    for(LL i = 0 ; i < m ; i++){
        a = a * (n - i) % p;
        b = b * (i + 1) % p;
    }
    return a * POW(b,p-2,p) % p;
}

LL lucas(int n,int m,int p){
    if(m == 0)
        return 1;
    return C(n%p,m%p,p)*lucas(n/p,m/p,p)%p;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m,p;
        scanf("%d%d%d",&n,&m,&p);
        cout<<lucas(n+m,m,p)<<"\n";
    }
    return 0;
}

发布了34 篇原创文章 · 获赞 7 · 访问量 1879

猜你喜欢

转载自blog.csdn.net/qq_43628761/article/details/98229478