之前介绍的费马小定理 ,用来处理 C ( n , m ) C(n,m) C(n,m)组合数取模 p p p,要求 p p p为质数, n , m n,m n,m小于 1 e 5 1e5 1e5(应该是受阶乘数组限制, 1 e 6 1e6 1e6差不多也行)
当 n 、 m n、m n、m达到1e8、1e10甚至更大的时候怎么办呢?这时候就需要Lacus定理。
Lacus定理
重点:可以解决
n
、
m
n、m
n、m比较大,
p
p
p为质数且较小的组合数问题
(我看这个博客讲的比较简单,一眼就能懂)
性质:
A、B是非负整数,p是质数。AB写成p进制:A=a[n]a[n-1]…a[0],B=b[n]b[n-1]…b[0]。
则组合数C(A,B)与C(a[n],b[n])C(a[n-1],b[n-1])…*C(a[0],b[0]) modp同余
即:Lucas(n,m,p)=c(n%p,m%p)*Lucas(n/p,m/p,p) (递归基础)
非常简单,上代码:
/*
* @Author: hesorchen
* @Date: 2020-04-14 10:33:26
* @LastEditTime: 2020-06-26 23:51:44
* @Link: https://hesorchen.github.io/
*/
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI acos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
// #define mod 1000000007
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
#define FRE \
{ \
freopen("in.txt", "r", stdin); \
freopen("out.txt", "w", stdout); \
}
inline ll read()
{
ll x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
//==============================================================================
ll jc[100100];
#define mod 12347 // 必须为质数
ll quick_pow(ll a, ll b) //快速幂
{
ll res = 1;
while (b)
{
if (b & 1)
res = res * a % mod;
a = a * a % mod;
b /= 2;
}
return res % mod;
}
void fjc() // 预处理阶乘
{
jc[0] = 1;
for (int i = 1; i <= mod; i++)
jc[i] = jc[i - 1] * i % mod;
}
ll C(ll n, ll m) //lacus定理
{
return jc[n] * quick_pow(jc[m], mod - 2) % mod * quick_pow(jc[n - m], mod - 2) % mod;
}
ll lucas(ll a, ll b) //递归求组合数
{
if (a % mod < b % mod) //!=========================这个还不清楚为什么要这样
return 0;
else if (a < mod && b < mod)
return C(a, b);
else
return (C(a % mod, b % mod) % mod * lucas(a / mod, b / mod));
}
int main()
{
fjc();
ll t;
cin >> t;
while (t--)
{
ll n, m;
cin >> n >> m;
cout << lucas(n, m) % mod << endl;
}
return 0;
}