9

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?

  • 5 mod 4 gives you a remainder of 1, -5 mod 4 gives -1. Makes sense to me – Huangism Sep 08 '14 at 14:39
  • Interestingly, [wolfram alpha](http://www.wolframalpha.com/input/?i=-5%254) agrees with you, but I think most programming languages will return `-1`. `.NET` returns `-1`. – Matt Burland Sep 08 '14 at 14:40
  • Look at MSDN doc : http://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." – Samuel Caillerie Sep 08 '14 at 14:40
  • The difference might be between `(-5)%4` and `-(5%4)`. In other words, it depends on the precedence of `%` versus `-`. Edit: [actually](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) it looks like `-` is supposed to have higher precedence than `%` (4 vs 5) – Matt Burland Sep 08 '14 at 14:41

5 Answers5

9

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

nullpotent
  • 9,162
  • 1
  • 31
  • 42
7

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

niklassc
  • 597
  • 1
  • 9
  • 24
2

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

FK82
  • 4,907
  • 4
  • 29
  • 42
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.

Vectornaut
  • 473
  • 5
  • 11
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
georg
  • 211,518
  • 52
  • 313
  • 390