乘法逆元 组合数学学习笔记

image

exgcd 时间复杂度:\(O(\log \max\{a, b\})\)
费马小定理时间复杂度:\(O(\log\ m)\) (快速幂的复杂度)

线性求逆元代码:

 inv[1] = 1;
 for (int i = 2; i <= n; ++i) {
     inv[i] = ((p - p / i) * inv[p % i] + p) % p;
 }

image

code:

void init() {
	fac[0] = inv[0] = 1;
	fac[1] = inv[1] = 1;
	for (int i = 2; i <= mod; ++i) {
		fac[i] = fac[i - 1] * i % mod;
		inv[i] = ((mod - mod / i) * inv[mod % i] + mod) % mod;
	}
	for (int i = 2; i <= mod; ++i) inv[i] = inv[i - 1] * inv[i] % mod;
}

inline ll C(ll n, ll m) {
	if (n < m) return 0;
	return fac[n] * inv[m] % mod * inv[n - m] % mod;
}

ll lucas(ll n, ll m) {
	if (m == 0) return 1;
	else return C(n % mod, m % mod) * lucas(n / mod, m / mod) % mod;
}

lucas 定理时间复杂度:\(O(p \log_{p}n)\)

posted @ 2023-06-25 20:54  Steven24  阅读(32)  评论(0编辑  收藏  举报