I have a struct representing a nonnegative rational number p/q:
struct rational {
uint64_t p;
uint64_t q; // invariant: always > 0
};
I would like to multiply my rational by a uint64 n and get an integer result, rounded down. That is, I would like to calculate:
uint64_t m = (n * r.p)/r.q;
while avoiding intermediate overflow in n * r.p. (Of course the final result may overflow, which is acceptable.)
How can I do this? Is there a way to do it without a high-multiply?
(I looked at boost::rational but it does not appear to provide this feature.)
Either 128-bits and you might use Karatsuba multiplication there; or you might use the Chinese Remainder Theorem to represent (n * r.p) mod p1 and also mod p2. The second might be slower.