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?
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
The reason is that %
is not a modulus but a remainder operator. See here
If you're using %
to do modular arithmetic, it doesn't matter (conceptually, at least) whether -5 % 4
evaluates to –1 or 3, because those two numbers are congruent modulo 4: for the purposes of modular arithmetic, they're the same.
...if the remainder is nonzero, there are two possible choices for the remainder, one negative and the other positive, and there are also two possible choices for the quotient. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and n. (http://en.wikipedia.org/wiki/Modulo_operation)
in python, which takes the sign of divisor:
-5 % 4 == 3 # -5 = (-2) * 4 + 3
in javascript, which takes the sign of divident:
-5 % 4 == -1 # -5 = (-1) * 4 - 1
© 2022 - 2024 — McMap. All rights reserved.
-1
..NET
returns-1
. – Pejsach(-5)%4
and-(5%4)
. In other words, it depends on the precedence of%
versus-
. Edit: actually it looks like-
is supposed to have higher precedence than%
(4 vs 5) – Pejsach