I\'m looking for a fast method to efficiently compute (a
⋅b
) modulo n
(in the mathematical sense of that) for
7 years later, I got a solution working in Visual Studio 2019
#include
#include
#pragma intrinsic(_umul128)
#pragma intrinsic(_udiv128)
// compute (a*b)%n with 128-bit intermediary result
// assumes n>0 and a*b < n * 2**64 (always the case when a<=n || b<=n )
inline uint64_t mulmod(uint64_t a, uint64_t b, uint64_t n) {
uint64_t r, s = _umul128(a, b, &r);
(void)_udiv128(r, s, n, &r);
return r;
}
// compute (a*b)%n with 128-bit intermediary result
// assumes n>0, works including if a*b >= n * 2**64
inline uint64_t mulmod1(uint64_t a, uint64_t b, uint64_t n) {
uint64_t r, s = _umul128(a % n, b, &r);
(void)_udiv128(r, s, n, &r);
return r;
}