Simple question, is it possible to simplify (or replace division or modulo by less-expensive operation)
(k/m)%n
where variables are integers and operators are C style division and modulo operators.
let me rephrase question slightly, except for case where variables are base2, under what conditions (e.g. some variable may be constant) can expression be simplified (or rephrased partially using base2 operations) to remove the division or modulo?
this is way for me to learn number theory, especially base2 tricks, rather than exercise in performance optimization
Thank you
For division with small constant denominator, you can use something like this.
The answer may not be precise depending on the inputs.
For division with small odd constant denominator, you can use the multiplicative inverse. The following constants apply to 32 bit division.
The
% 2^32is of course free on 32 bit integers. To adopt this to even numbers factor out the twos and apply them later.Hackers Delight has a chapter on integer division.
The simple modulus and division for powers of two.