I have a function Java which looks like this:
private static long fieldPrime = 4294967291L; // 2^32-5
public final static long modMult(long a, long b) {
long r = (a*b) % fieldPrime;
return r;
}
It multiplies two values (which are guaranteed to be between 0 and 2^32-5) and then does modulo a large prime.
It works for most numbers but sometimes a*b overflows and this causes the function to return the wrong value. Unfortunately Java doesn't support unsigned longs (which would have solved the issue) and BigInteger is too slow. Can I solve this some other way? I.e. can I adjust r somehow when I detect overflow (in this case a*b < 0 always means it has overflowed).