大组合数取余模板【Lucas定理】

求C(n, m) % mod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
long long fact[200200];
long long inv[200200];
const int mod = 1e9 + 7;
long long qpow(long long x, long long n)
{
    long long ans = 1;
    while (n)
    {
        if (n & 1)
            ans = ans * x % mod;
        x = x * x % mod;
        n >>= 1;
    }
    return ans;
}
 
void init()
{
    fact[0] = 1;
    for (int i = 1; i < 200005; i++)
        fact[i] = fact[i - 1] * i % mod;
    for (int i = 0; i < 200005; i++)
        inv[i] = qpow(fact[i], mod - 2);
}
 
long long C(int n, int m)
{
    return fact[n] * inv[n - m] % mod * inv[m] % mod;
}
 
int main()
{
    init();
    int n, m;
    while(cin >> n >> m) {
        cout << C(n, m) << endl;
    }
}
原文地址:https://www.cnblogs.com/bestwzh/p/6754139.html