卢卡斯定理(模板)

卢卡斯定理是一个在组合数学中用于计算特定组合数值的公式,尤其适用于大数情况。本文将探讨该定理及其在解决编程模板题如Luogu P3807中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

卢卡斯定理

卢卡斯定理主要用来求大数组合数。
模板题: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值