Search code examples
javascriptmodular-arithmetic

Javascript Modular Arithmetic


Javascript evaluates the following code snippet to -1.

-5 % 4

I understand that the remainder theorem states a = bq + r such that 0 ≤ r < b. Given the definition above should the answer not be 3? Why does JavaScript return -1?


Solution

  • Because it's a remainder operator, not a modulo. But there's a proposal for a proper one.

    A quote from Ecma 5.1

    remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive