Recently I\'ve been confused about the modulo operator, %
.
It\'s known that a % b == a-a/b*b
when we have integers a
and b>
Except for powers of 2, where the modulo operator can (and in most optimizing compilers is) be turned into a simple bitwise operation, I'm afraid the only way to do it is the hard way. Explanation is http://en.wikipedia.org/wiki/Modulo_operation
In another answer, @Henk Holterman points out that some CPUs do it in the microcode, leaving the remainder in a register while doing an integer divide, which means the modulo instruction can be reduced to an integer divide and return the remainder. (I'm adding that information here because this answer has already been accepted.)