My program frequently requires the following calculation to be performed:
Given:
The basic correct approach to this is simply (uint64_t)x*n/d
. That's optimal assuming d
is variable and unpredictable. But if d
is constant or changes infrequently, you can pre-generate constants such that exact division by d
can be performed as a multiplication followed by a bitshift. A good description of the algorithm, which is roughly what GCC uses internally to transform division by a constant into multiplication, is here:
http://ridiculousfish.com/blog/posts/labor-of-division-episode-iii.html
I'm not sure how easy it is to make it work for a "64/32" division (i.e. dividing the result of (uint64_t)x*n
), but you should be able to just break it up into high and low parts if nothing else.
Note that these algorithms are also available as libdivide.