防止一切因为忘记模数而导致爆 0 的事情发生!
template <int mod>
struct mint {
unsigned int _v;
mint() : _v(0) {}
template <class T>
mint(T v) {
ll x = (ll)(v % (ll)(umod()));
if (x < 0) x += umod();
_v = (unsigned int)(x);
}
mint(bool v) { _v = ((unsigned int)(v) % umod()); }
static constexpr unsigned int umod() { return mod; }
unsigned int val() const { return _v; }
mint& operator++() {
_v++;
if (_v == umod()) _v = 0;
return *this;
}
mint& operator--() {
if (_v == 0) _v = umod();
_v--;
return *this;
}
mint operator++(int) {
mint result = *this;
++*this;
return result;
}
mint operator--(int) {
mint result = *this;
--*this;
return result;
}
mint& operator+=(const mint& rhs) {
_v += rhs._v;
if (_v >= umod()) _v -= umod();
return *this;
}
mint& operator-=(const mint& rhs) {
_v -= rhs._v;
if (_v >= umod()) _v += umod();
return *this;
}
mint& operator*=(const mint& rhs) {
ull z = _v;
z *= rhs._v;
_v = (unsigned int)(z % umod());
return *this;
}
mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }
mint operator+() const { return *this; }
mint operator-() const { return mint() - *this; }
mint pow(ll n) const {
assert(n >= 0);
mint x = *this, r = 1;
for (; n; n >>= 1) {
if (n & 1) r *= x;
x *= x;
}
return r;
}
mint inv() const { return pow(umod() - 2); }
friend mint operator+(const mint& lhs, const mint& rhs) { return mint(lhs) += rhs; }
friend mint operator-(const mint& lhs, const mint& rhs) { return mint(lhs) -= rhs; }
friend mint operator*(const mint& lhs, const mint& rhs) { return mint(lhs) *= rhs; }
friend mint operator/(const mint& lhs, const mint& rhs) { return mint(lhs) /= rhs; }
friend bool operator==(const mint& lhs, const mint& rhs) { return lhs._v == rhs._v; }
friend bool operator!=(const mint& lhs, const mint& rhs) { return lhs._v != rhs._v; }
};
标签:return,int,rhs,umod,Modular,operator,const,mint,模板
From: https://www.cnblogs.com/ckb2008/p/modint-template.html