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.)