(1)擴展歐幾里得
LL exgcd(LL a, LL b, LL &x, LL &y)
{
if (b == 0)
{
x = 1;
y = 0;
return a;
}
LL r = exgcd(b, a % b, x, y);
LL t = x % mod;
x = y % mod;
y = ((t - a / b * y) % mod + mod) % mod;
return r;
}
求a對於b的逆元x
(2)費馬小定理 要求p爲素數
LL quick_mod(LL x, LL n, LL p)
{
LL res = 1;
while(n)
{
if (n & 1)
res = res * x % p;
x = x * x % p;
n >>= 1;
}
return res;
}
LL inv(LL x, LL p)
{
return quick_mod(x, p-2, p);
}
(3)初始化記錄逆元
void init()
{
F[0] = 1; F[1] = 1;//階乘
for (int i = 2; i < maxn; ++i)
F[i] = F[i-1] * i % p;
invF[maxn - 1] = quick_mod(F[maxn - 1], p-2);//階乘逆元
for (int i = maxn - 2; i >= 0; --i)
invF[i] = invF[i+1] * (i + 1) % p;
inv[1] = 1;//1-n逆元
for (int i = 2; i < max; ++i)
inv[i] = (p - p / i) * inv[p % i] % p;
}