I have a very specific algorithm that requires doing a lot of calculations of (a * b) / c
in Java, where:
a
andb
are 64-bit longsa*b
may overflow into 128 bits (not always, but at least reasonably common)c
is a 64-bit long- The result
(a * b) / c
should fit in a 64-bit long (we need to detect if it overflows, but the result doesn't matter in this case)
Is there an efficient algorithm to do this kind of fused multiply and divide? I naturally tried using BigInteger
which works fine but is unacceptably slow (this needs to be high performance code).