尚不完善的数学 namespace
albertting · · 科技·工程
懒懒的,用到什么补什么吧~
namespace Math {
vector<ll> fac, invfac;
static ll P;
ll qpow(ll a, ll b, ll p = P) { // Quick pow.
ll res = 1 % p;
a %= p;
while(b > 0) {
if(b & 1) res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
ll exgcd(ll a, ll b, ll &x, ll &y) { // exGCD.
if(b == 0) {
x = 1; y = 0;
return a;
}
ll x1, y1;
ll g = exgcd(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return g;
}
pair<bool, ll> inv(ll a, ll m) { // Use exGCD to find the inverse.
ll x, y;
ll g = exgcd(a, m, x, y);
if(g != 1 && g != -1) return {false, -1};
x = (x % m + m) % m;
return {true, x};
}
ll inv(ll a) { return qpow(a, P - 2); } // Use Fermat's Little Theorem to find the inverse.
void init(ll n, ll p) { // Initialization of factorial and its inverse (for efficiently computing permutations and combinations).
P = p;
fac.resize(n + 1);
invfac.resize(n + 1);
fac[0] = 1;
for(ll i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % P;
invfac[n] = qpow(fac[n], P - 2);
for(ll i = n; i >= 1; i--) invfac[i - 1] = invfac[i] * i % P;
}
ll C(ll n, ll k) { // Calculate the combination.
if(k < 0 || k > n) return 0;
return fac[n] * invfac[k] % P * invfac[n - k] % P;
}
ll A(ll n, ll k) { // Calculate the permutation.
if(k < 0 || k > n) return 0;
return fac[n] * invfac[n - k] % P;
}
ll mod_add(ll a, ll b, ll p = P) { // Addition in the modular sense.
ll s = a + b;
if(s >= p) s -= p;
return s;
}
ll mod_minus(ll a, ll b, ll p = P) { // Subtraction in modular sense.
ll s = a - b;
if(s < 0) s += p;
return s;
}
ll mod_mul(ll a, ll b, ll p = P) { // Multiplication in the modular sense.
return a * b % p;
}
ll mod_mul_protected(ll a, ll b, ll p = P) { // Overflow-protected multiplication in modular arithmetic.
if(a < b) swap(a, b);
ll res = 0;
a %= p;
while(b > 0) {
if(b & 1) res = mod_add(res, a, p);
a = (a << 1) % p;
b >>= 1;
}
return res;
}
ll mod_div(ll a, ll b) { // Division in the modular sense.
return mod_mul(a, inv(b));
}
ll mod_div_protected(ll a, ll b) { // Overflow-protected division in modular sense.
return mod_mul_protected(a, inv(b));
}
ll range_mul(ll st, ll ed, ll p = P) { // Calculate the product of consecutive integers.
st %= p, ed %= p;
if(st > ed) return 1ll;
if(st == 0) return 0ll;
if(ed < (ll)fac.size() && p == P) return mod_mul(fac[ed], invfac[st - 1]);
ll res = 1;
for(ll i = st; i <= ed; i++) res = mod_mul(res, i, p);
return res;
}
};
- [x] 模意义下加法;
- [ ] 模意义下区间累加;
- [x] 模意义下减法;
- [x] 模意义下乘法;
- [x] 模意义下防溢出安全乘法;
- [x] 模意义下区间累乘;
- [ ] 模意义下防溢出安全区间累乘;
- [x] 模意义下除法;
- [x] 模意义下防溢出安全除法;
- [x] 快速幂;
- [x] GCD;
- [x] exGCD;
- [x] exGCD 求逆元;
- [x] FLT 求逆元;
- [x] 线性预处理阶乘及其逆元;
- [x] 组合数;
- [x] 排列数;
- [ ] CRT;
- [ ] 线性筛;
- [ ] 线性筛预处理
\varphi 函数; - [ ]
\varphi 函数; - [ ] 内置分数类