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?
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
Most programming languages use a symmetric modulo which is different than the mathematical one for negative values.
The mathematical modulo can be computed using the symmetric modulo like this:
a mod b = ((a % b) + b) % b
mod
mathematical modulo
%
symmetric modulo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With