zcmu 1549: Number of combinations (Lucas theorem)

Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1549

Topic

Give you n, m, p, ask you to find the number of combinations C(n, m)%p

Range: (1 <= m <= n <= 10^9, m <= 10^4, 0< p <100, p is a prime number)

Ideas

The range of n and m is very large. If C is directly calculated, t will be obtained, but here the modulus p is small, so you can start with p.

C(n, m) = n! * (n - m)! % p * m! % p

Apply Lucas' theorem : for non-negative integer m, n and prime number p

C_{n}^{m}\equiv \prod_{i=0}^{k}C_{m_i}^{n_i} (mod \ p), Where m = m_kp ^ k + ... + m_1p + m_0, n = n_kp ^ k + ... + n_1p + n_0is the p-ary expansion of m and n

When n<m, stipulateC_{n}^{m}=0

ac code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 105;
ll fac[maxn], inv[maxn], p;
// fac[i]表示i的阶乘对p取模
// inv[i]表示i的阶乘的逆元对p取模
void init(ll n){
    fac[0] = 1;
    for(int i = 1; i <= n; i ++) fac[i] = fac[i - 1] * i % p;
    inv[n] = _pow(fac[n], p - 2);
    for(int i = n - 1; i >= 0; i --) inv[i] = inv[i + 1] * (i + 1) % p;
}
ll C(ll n, ll m){
    if(n < m) return 0;
    return fac[n] * inv[m] % p * inv[n - m] % p;
}
ll lucas(ll n, ll m){//卢卡斯定理
    if(m == 0) return 1 % p;
    return lucas(n / p, m / p) * C(n % p, m % p) % p;
}
ll _pow(ll a, ll b){
    ll ans = 1;
    while(b){
        if(b & 1) ans = ans * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return ans;
}
int main(){
    int t; scanf("%d", &t);
    while(t --){
        ll n, m;
        scanf("%lld%lld%lld",&n,&m,&p);
        init(p - 1);
        printf("%lld\n", lucas(n, m));
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/112710201