Advertisement
STANAANDREY

modInt

May 8th, 2021 (edited)
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template<int mod> struct ModInt{
  4.     int x;
  5.     ModInt () : x(0) {}
  6.     ModInt (int64_t x) : x(x >= 0 ? x % mod : (mod - -x % mod) % mod) {}
  7.     ModInt &operator += (const ModInt &p){
  8.         if ((x += p.x) >= mod) x -= mod;
  9.         return *this;
  10.     }
  11.     ModInt &operator -= (const ModInt &p) {
  12.         if ((x += mod - p.x) >= mod) x -= mod;
  13.         return *this;
  14.     }
  15.     ModInt &operator *= (const ModInt &p) {
  16.         x = (int64_t) x * p.x % mod;
  17.         return *this;
  18.     }
  19.     ModInt &operator /= (const ModInt &p) {
  20.         *this *= p.inverse();
  21.         return *this;
  22.     }
  23.     ModInt &operator ^= (int64_t p) {
  24.         ModInt res = 1;
  25.         for (; p; p >>= 1) {
  26.             if (p & 1) res *= *this;
  27.             *this *= *this;
  28.         }
  29.         return *this = res;
  30.     }
  31.     ModInt operator - () const { return ModInt(-x); }
  32.     ModInt operator + (const ModInt &p) const { return ModInt(*this) += p; }
  33.     ModInt operator - (const ModInt &p) const { return ModInt(*this) -= p; }
  34.     ModInt operator * (const ModInt &p) const { return ModInt(*this) *= p; }
  35.     ModInt operator / (const ModInt &p) const { return ModInt(*this) /= p; }
  36.     ModInt operator ^ (int64_t p) const { return ModInt(*this) ^= p; }
  37.     bool operator == (const ModInt &p) const { return x == p.x; }
  38.     bool operator != (const ModInt &p) const { return x != p.x; }
  39.     explicit operator int() const { return x; }
  40.     ModInt &operator = (const int p) { x = p; return *this;}
  41.     ModInt inverse() const {
  42.         int a = x, b = mod, u = 1, v = 0, t;
  43.         while (b > 0) {
  44.             t = a / b;
  45.             a -= t * b;
  46.             std::swap(a, b);
  47.             u -= t * v;
  48.             std::swap(u, v);
  49.         }
  50.         return ModInt(u);
  51.     }
  52.     friend std::ostream & operator << (std::ostream &stream, const ModInt<mod> &p) {
  53.         return stream << p.x;
  54.     }
  55.     friend std::istream & operator >> (std::istream &stream, ModInt<mod> &a) {
  56.         int64_t x;
  57.         stream >> x;
  58.         a = ModInt<mod>(x);
  59.         return stream;
  60.     }
  61. };
  62.  
  63. int main() {
  64.  
  65.     return 0;
  66. }
  67.  
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement