自用 modint。
除开乘方是 的,除法是 的,其余运算单次 。
namespace moduloInteger
{
// edited by staring
// link: https://www.luogu.com.cn/user/642907
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
struct Barrett
{
u32 _m; u64 im;
explicit Barrett(u32 m)
: _m(m), im(u64(-1) / m + 1){};
u32 mod(u64 x)
{
if(x < _m) return x;
u64 y = u64(u128(x) * im >> 64);
u64 z = y * _m;
return u32(x >= z ? x - z : x - z + _m);
}
u32 inv(u32 a)
{
u32 r = 1;
while(a > 1)
{
u32 t = _m / a;
r = mod(u64(r) * (_m - t));
a = _m - t * a;
}
return r;
}
};
template<i32 P>
struct MODINT
{
using mi = MODINT;
private:
i32 x;
static Barrett bt;
public:
constexpr MODINT() : x(0){}
constexpr MODINT(i32 _x, std::nullptr_t) : x(_x){}
constexpr MODINT(i64 _x) : x(normal(bt.mod(_x))){}
constexpr i32 normal(i32 x)
{return x >= P ? x - P : x + (x >> 31 & P);}
constexpr i32 val() const {return x;}
constexpr static i32 mod() {return P;}
constexpr explicit operator bool() const {return x;}
constexpr mi operator-() const {return mi(P - x);}
constexpr mi& operator+=(const mi& rhs) {x = normal(x + rhs.val()); return *this;}
constexpr mi& operator-=(const mi& rhs) {x = normal(x - rhs.val()); return *this;}
constexpr mi& operator++() {return (*this) += 1;}
constexpr mi& operator--() {return (*this) -= 1;}
constexpr mi& operator*=(const mi& rhs) {x = bt.mod(u64(x) * rhs.val()); return *this;}
constexpr mi& operator/=(const mi& rhs) {return *this *= rhs.inv();}
constexpr mi inv() const
{
assert(x != 0);
return mi(bt.inv(x), nullptr);
}
constexpr mi pow(u64 b) const
{
assert(x >= 0);
mi a = *this, c = 1;
while(b)
{
if(b & 1) c *= a;
a *= a, b >>= 1;
}
return c;
}
constexpr friend mi operator+(const mi& lhs, const mi& rhs)
{auto res = lhs; res += rhs; return res;}
constexpr friend mi operator-(const mi& lhs, const mi& rhs)
{auto res = lhs; res -= rhs; return res;}
constexpr friend mi operator*(const mi& lhs, const mi& rhs)
{auto res = lhs; res *= rhs; return res;}
constexpr friend mi operator/(const mi& lhs, const mi& rhs)
{auto res = lhs; res /= rhs; return res;}
constexpr friend mi operator++(mi& x, i32)
{auto res = x; x += 1; return res;}
constexpr friend mi operator--(mi& x, i32)
{auto res = x; x -= 1; return res;}
constexpr friend std::istream& operator>>(std::istream& is, mi& x)
{u64 v; is >> v; x = v; return is;}
constexpr friend std::ostream& operator<<(std::ostream& os, const mi& x)
{os << x.val(); return os;}
constexpr bool operator==(const mi& rhs) const {return x == rhs.val();}
constexpr bool operator!=(const mi& rhs) const {return x != rhs.val();}
};
template<i32 P> Barrett MODINT<P>::bt(P);
}