I want to multiply two integers modulo another (prime) integer (approximately 50 bit in length) in C.
uint64_t x = ...;
uint64_t y = ...;
uint64_t q = ...;
uint64_t z = (x*y) % q;
This would produce a 64 bit integer smaller than q but unfortunately x%q * y%q
is way too large for a 64 bit type. So it overflows before I can calculate the remainder.
I thought about some workarounds:
- using gcc's
__uint128_t
would violate the C standard and wouldn't work with other compilers - cast variables to
double
orlong double
but the result wouldn't be correct due to floating point inaccuracy - using a multiple precision library like GMP would work but that introduces a new project dependency and maybe comes with some overhead
- writing an own multiplication function for that purpose, but as far as I know I would need assembly, so portability is gone
Are there other options or what would you recommend?
EDIT: I forgot to mention, that a self written solution is only worth doing if it is efficient. For example doing dozens of inefficient % operations would be bad.