Javascript Modular Arithmetic
Asked Answered
Z

5

10

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?

Zeringue answered 8/9, 2014 at 14:35 Comment(4)
5 mod 4 gives you a remainder of 1, -5 mod 4 gives -1. Makes sense to meAccidie
Interestingly, wolfram alpha agrees with you, but I think most programming languages will return -1. .NET returns -1.Pejsach
Look at MSDN doc : msdn.microsoft.com/en-us/library/ie/9f59bza0%28v=vs.94%29.aspx. "The sign of result is the same as the sign of number1. The value of result is between 0 and the absolute value of number2."Dipody
The difference might be between (-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
D
10

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

Dangelo answered 8/9, 2014 at 14:40 Comment(0)
L
9

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

Lordan answered 17/11, 2017 at 15:45 Comment(1)
I guessed that, but wasn't sure if it was correct or not. Your answer saved me.Truett
L
2

The reason is that % is not a modulus but a remainder operator. See here

Litch answered 8/9, 2014 at 14:41 Comment(0)
F
1

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.

Fitter answered 24/4, 2015 at 23:26 Comment(0)
A
0

...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
Archaic answered 8/9, 2014 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.