Skip to content

Commit

Permalink
math/fast_mod
Browse files Browse the repository at this point in the history
  • Loading branch information
teapotd committed Apr 5, 2024
1 parent 57ebecd commit 74d9c54
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 23 deletions.
16 changes: 16 additions & 0 deletions src/math/fast_mod.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#pragma once
#include "../template.h"

using ull = uint64_t;

// Compute a % b faster, where b is constant,
// but not known at compile time.
// Returns value in range [0,2b).
//! Source: https://github.com/kth-competitive-programming/kactl/blob/main/content/various/FastMod.h
struct FastMod {
ull b, m;
FastMod(ull a) : b(a), m(-1ULL / a) {}
ull operator()(ull a) { // a % b + (0 or b)
return a - ull((__uint128_t(m)*a)>>64) * b;
}
};
23 changes: 0 additions & 23 deletions src/math/montgomery.h

This file was deleted.

17 changes: 17 additions & 0 deletions tests/own/math/fast_mod.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "../../../src/math/fast_mod.h"
#include "../base_test.hpp"

void deterministic() {
}

void fuzz() {
rep(i, 0, 20'000'000) {
ull a = randRange<ull>(0, 1e18);
ull b = randRange<ull>(1, 1e18);
ull got = FastMod(b)(a);
assert(got == a%b || got == a%b+b);
}
}

void benchmark() {
}

0 comments on commit 74d9c54

Please sign in to comment.