finds.dev

lemire/fastmod

A C/C++ header file for fast 32-bit division remainders (and divisibility tests) on 64-bit hardware.

View on GitHub

★ 350C++Apache-2.0updated Apr 2026

// the take

A single header file implementing Daniel Lemire's fast modulo/division trick for 32-bit divisors on 64-bit hardware. The trick replaces division with a multiply-and-shift using a precomputed magic number, which is faster when you're applying the same divisor repeatedly — hash tables being the canonical use case. Not general-purpose; only useful in tight loops where you control the divisor.

The technique is backed by a published paper with actual math, not just empirical cargo-culting. Header-only with a dead-simple API — precompute M once, call fastmod_u32 in the hot loop, done. Exhaustive test mode covers all 32-bit dividends for correctness, which matters for a low-level numeric primitive. Benchmarks are real Skylake numbers with a specific compiler, not made-up percentages.

The 64-bit variant is experimental and not supported on MSVC, so if you're on Windows or need 64-bit divisors you're on your own. At 350 stars it's niche enough that you should expect to debug issues yourself — the issue tracker is sparse. Modern compilers (GCC, Clang) already apply this optimization automatically for compile-time-constant divisors, so you only gain something when the divisor is runtime-determined but repeated. No CMake install target or package manager support, so integrating it into a larger build requires manual file copying.

We read the README, the directory tree and a key source file in July 2026. Nobody pays to be listed. How we judge →

// at a glance

Stars
350
Forks
30
Language
C++
License
Apache-2.0
Last commit
11 Apr 2026

// nearby

If fastmod isn't quite it.

All repos →