Skip to content

Commit

Permalink
add: dynamic mod int
Browse files Browse the repository at this point in the history
  • Loading branch information
kogetsu7 committed Jan 1, 2025
1 parent fc8224c commit 322939d
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 5 deletions.
112 changes: 112 additions & 0 deletions math/dynamic_mod_int.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#pragma once

#include "../template/template.hpp"

/**
* @brief Dynamic Mod Int
* @note 仮実装
*/
class DynamicModInt {
private:
int v;
static int m;

public:
DynamicModInt() : v(0) {}
DynamicModInt(ll _v) : v(int(((_v % m) + m) % m)) {}

static void set_mod(int _m) {
m = _m;
assert(m <= INT_MAX / 2);

return;
}

static DynamicModInt raw(int _v) {
DynamicModInt res;
res.v = _v;

return res;
}

static int mod() { return m; }
int val() const { return v; }

friend bool operator==(const DynamicModInt& lhs, const DynamicModInt& rhs) {
return lhs.v == rhs.v;
}

friend bool operator!=(const DynamicModInt& lhs, const DynamicModInt& rhs) {
return !(lhs == rhs);
}

DynamicModInt& operator+=(const DynamicModInt& rhs) {
v += rhs.v;
if (m <= v) {
v -= m;
}

return *this;
}

DynamicModInt& operator-=(const DynamicModInt& rhs) {
if (v < rhs.v) {
v += m;
}
v -= rhs.v;

return *this;
}

DynamicModInt& operator*=(const DynamicModInt& rhs) {
v = (ull(v) * rhs.val()) % m;

return *this;
}

DynamicModInt& operator/=(const DynamicModInt& rhs) {
assert(rhs.v != 0);

return *this *= rhs.inv();
}

friend DynamicModInt operator+(const DynamicModInt& lhs,
const DynamicModInt& rhs) {
return DynamicModInt(lhs) += rhs;
}

friend DynamicModInt operator-(const DynamicModInt& lhs,
const DynamicModInt& rhs) {
return DynamicModInt(lhs) -= rhs;
}

friend DynamicModInt operator*(const DynamicModInt& lhs,
const DynamicModInt& rhs) {
return DynamicModInt(lhs) *= rhs;
}

friend DynamicModInt operator/(const DynamicModInt& lhs,
const DynamicModInt& rhs) {
return DynamicModInt(lhs) /= rhs;
}

DynamicModInt pow(ll y) const {
DynamicModInt res = raw(1);
DynamicModInt x = *this;

while (0 < y) {
if (y & 1) {
res *= x;
}

x *= x;
y >>= 1;
}

return res;
}

DynamicModInt inv() const { return pow(m - 2); }
};

int DynamicModInt::m = 998244353;
8 changes: 3 additions & 5 deletions test/math/binomial.test.cpp
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
#define PROBLEM "https://judge.yosupo.jp/problem/binomial_coefficient_prime_mod"

#include "../../math/binomial.hpp"
#include "../../math/dynamic_mod_int.hpp"
#include "../../template/template.hpp"

#include <atcoder/modint>
using namespace atcoder;

int main() {
int T, M;
cin >> T >> M;

modint::set_mod(M);
Binomial<modint> bin(min(M - 1, 10000000));
DynamicModInt::set_mod(M);
Binomial<DynamicModInt> bin(min(M - 1, 10000000));

while (T--) {
int n, k;
Expand Down

0 comments on commit 322939d

Please sign in to comment.