Created
April 18, 2019 23:27
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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