Given three integers, a, band c with a,b <= c < INT_MAX I need to compute (a * b) % c but a * b can overflow if the values are too large, which gives the wrong result.
Is there a way to compute this directly through bithacks, i.e. without using a type that won’t overflow for the values in question?
Karatsuba’s algorithm is not really needed here. It is enough to split your operands just once.
Let’s say, for simplicity’s sake, that your numbers are 64-bit unsigned integers. Let k=2^32. Then
Now
a1*b1 % ccan be computed immediately, the rest could be computed by alternately performingx <<= 1andx %= c32 or 64 times (since (u*v)%c=((u%c)*v)%c). This could ostensibly overflow ifc >= 2^63. However, the nice thing is that this pair of operations need not be performed literally. Eitherx < c/2and then you only need a shift (and there’s no overflow), orx >= c/2and(and there’s no overflow again).