Modulo and Remainder Operator
§Euclidean division
1 | Given two integers a and b, with b ≠ 0, there exist unique integers q and r such that |
In mathematics the result of the modulo operation is the remainder of the Euclidean division.
In C, the %
operator is often mistakenly referred as modulo operator, but it in fact is the remainder operator, satisfying:
(a / b) * b + a % b = a
Haskell is a language exposes both modulo and remainder operator
1 | (x `quot` y)*y + (x `rem` y) == x |
If the divisor is of power of 2, a quick way calculating the modulo is to using & (b-1)
, which assumes two’s complement, but it’s ubiquitous anyway.