How does Javascript handle a negative modulo? (`-5 % 20`)

-5 % 20 should be 15. When I enter this it returns -5. Is this a javascript thing or an artifact of this simulator?

thanks.

Hello, @bit5009167409. Welcome to the forums.

20 goes into -5 how many times? 0 right? What is the remainder? -5 correct?
-5 + 20 = 15, but -5 % 20 = -5
The output is correct.

Node.js:

> -5 + 20
15
> -5 % 20
-5
73 Likes

Case 1:
101/ 11 = 99 remainder 2
or
101 = 11 * 99 + 2

Case 2:
-11 / 3 =

-11 = -4*3 + 1
So the remainder is 1.

Remainders must always be positive.

Reference: Discrete Math & Its Applications, K. Rosen, 7th Edition page 217.

So -5 / 20 =

-5 = -1 * 20 + 15

So the remainder is 15.

35 Likes

I’m not a mathematician, so I won’t argue, but this is curious. It would seem per your reference that Python knows how to do math where JavaScript and Haskell do not. It may also be that Python does the actual math where JavaScript and Haskell behave in a predictable manner for programmers. Idk

Examples:

//JavaScript
> -5 % 20
-5

//#Python
>>> -5 % 20
15

//-- Haskell
Prelude> -5 `mod` 20
-5

//C++
#include <iostream>

int main() {
  std::cout << -5 % 20; // -5
}

//C#
using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine (-5 % 20); // -5
  }
}

//Java
public class YourClassNameHere {
    public static void main(String[] args) {
    System.out.println(-5 % 20); // -5
    }
}

//#Ruby
puts -5 % 20 // 15

//Swift
print(-5 % 20) // -5

Interesting. Python & Ruby behave as you’ve described the correct answer should be, but the others do not. :thinking:

Perhaps someone with much more knowledge than me could weigh in. @ionatan, @mtf, @appylpye

Edit:
Haskell produces different results depending on how the mod method is used:

Prelude> mod (-5) 20
15
Prelude> (-5) `mod` 20
15
Prelude> -5 `mod` 20
-5

I suppose you just have to review the docs for the language that you’re using to know what the expected behavior is. Here’s a link to the JavaScript docs on the remainder operator.

40 Likes

Thanks for checking all of those out! In the big picture, I don’t think it matters. I just found it curious! In the very very rare event that the topic comes up, I guess its good to know that one can get different interpretations.

Thank you.

9 Likes

Other than not getting the expected outcome. I, not having much of a background in math, (at least not a lot that I remember anymore) saw the expected outcome. With your background, you saw a math error. Thanks for asking your original question. I learned something. :slightly_smiling_face:
Happy coding!

10 Likes

In modular arithmetic things go around, like a clock. You’ll always end up with a result in the valid range. For a clock, 23 + 4 is 3
There are two similar operations, rem and mod, and two ways to divide to go with them.

Haskell’s prelude exports both of those functions, and both ways to divide (rem mod div quot). (watch out with operator precedence) The documentation there also mentions their differences and relations:
https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:quot
I suppose languages that give special meaning to % pick one or the other and then match division with it (div mod or quot rem) … and if you care about the difference then you’d probably notice.

7 Likes

The remainder / modulus operator ( % ) returns the remainder after (integer) division. This operator returns the remainder left over when one operand is divided by a second operand. When the first operand is a negative value, the return value will always be negative , and vice versa for positive values.

Case 1:
-5%20= -5 (here, the operation will perform just like 5%20, and the remainder will have negative sign to it)

Case 2:
-50%20= -10 (50%20=10 , hence the answer here is -10 because first operand is negative integer)

Case3:
-500%20= -0 (even zero will have negative sign to it in JavaScript)

9 Likes

On paper it would be zero, but in this case the computer sees the disparity in the signs so automatically assigns the negative sign to the remainder. It has no meaning. Purely mechanics.

5 Likes

yes you are right.
Thank you for your response.

1 Like

Weird, I was also expecting it to be 15 as per your correct explanation but after I read JS doc it seems if we have the denominator’s value greater than the nominator’s then the result is always the nominator.

1 Like

The reasoning is simple. The modulo is the remainder. If the numerator (the dividend in division) is less than the denominator (divisor in division) then the quotient is zero, with the numerator remaining.

6 Likes

According the JS documentation in the link provided above:

Note that while in most languages, ‘%’ is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. For positive values, the two are equivalent, but when the dividend and divisor are of different signs, they give different results. To obtain a modulo in JavaScript, in place of a % n , use ((a % n ) + n ) % n .

8 Likes

I dont seem to understand how the answer is 5 yet 20 is a multiple of 5 so in the first place i thought it shouldnt have a remainder. correct me please

5 divided by 20 is zero, remainder 5.

1 Like

I get you. Thank you i now get it well.

1 Like

I would like to point out that negative modulos are not always defined the same way, and depending on what you use you can get a different result. Take 5 % (-3) for example; I get 2 from some places, -1 from other places and 1 from other places:

C++, JS and Java give 2:
image
image

.
Python and Google’s calculator give -1:
image
image

.
calculators.org gives 1:

.
Basically, there is no universally accepted way of doing this. There are reasons for each (such as the debate over 1/0 = Infinity), and you should always make sure you know what you are doing when using a negative modulo. Ideally, just make your own function to calculate it so there is no ambiguity

I am not getting remainder. How it is calculated. if We Divide -5/20 then quotient is 0.25 and remainder is 0. Then How it is -5 or 15. Please Clear my doubt. How -5%20 or any remainder is calculated in programming.

1 Like

Think in terms of integer division where the quotient is a whole number.

   ___0_
20 ) -5
     -0    0 * 20
    ----
     -5    Remainder


          quotient
        -----------
divisor ) Dividend

         -----------
          Remainder
q * d = D - R
6 Likes

MDN states that the “%” operator is actually a remainder operator: " ‘%’ is a remainder operator" in languages like JavaScript, Java, C, Haskell, etc. It always takes the sign of the dividend, and that’s why it behaves differently to what you would expect.

MDN: "To obtain a modulo in JavaScript, in place of a % n, use: ((a % n ) + n ) % n "