What is the most accurate way I can do a multiply-and-divide operation for 64-bit integers that works in both 32-bit and 64-bit programs (in Visual C++)? (In case of overflow, I need the result mod 264.)
(I’m looking for something like MulDiv64, except that this one uses inline assembly, which only works in 32-bit programs.)
Obviously, casting to double and back is possible, but I’m wondering if there’s a more accurate way that isn’t too complicated. (i.e. I’m not looking for arbitrary-precision arithmetic libraries here!)
Since this is tagged Visual C++ I’ll give a solution that abuses MSVC-specific intrinsics.
This example is fairly complicated. It’s a highly simplified version of the same algorithm that is used by GMP and
java.math.BigIntegerfor large division.Although I have a simpler algorithm in mind, it’s probably about 30x slower.
This solution has the following constraints/behavior:
Note that this is for the unsigned integer case. It’s trivial to build a wrapper around this to make it work for signed cases as well. This example should also produce correctly truncated results.
This code is not fully tested. However, it has passed all the tests cases that I’ve thrown at it.
(Even cases that I’ve intentionally constructed to try to break the algorithm.)
Note that if you don’t need a perfectly truncated result, you can remove the last loop completely. If you do this, the answer will be no more than 2 larger than the correct quotient.
Test Cases:
Output: