Skip to content

Instantly share code, notes, and snippets.

@simonlindholm
Created April 18, 2019 23:27
Show Gist options
  • Save simonlindholm/0aa4c140e58a584264f929b338ef870a to your computer and use it in GitHub Desktop.
Save simonlindholm/0aa4c140e58a584264f929b338ef870a to your computer and use it in GitHub Desktop.
Fast modulo (via Barrett reduction, works for arbitrary 64-bit integers except d = 1)
typedef long long ll;
typedef unsigned long long ull;
typedef __uint128_t L;
struct Barrett {
ull d, m;
Barrett(ull d) : d(d), m(ull((L(1) << 64) / d)) {}
ull reduce(ull a) {
ull q = (ull)((L(m) * a) >> 64);
ull r = a - q * d;
if (r >= d) r -= d;
return r;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment