Skip to content Skip to sidebar Skip to footer

Javascript Modulo Operator Behaves Differently From Other Languages

According to Wikipedia, the modulo operator (remainder of integer division) on n should yield a result between 0 and n-1. This is indeed the case in python: print(-1%5) # outputs 4

Solution 1:

If by "modulus" you understand the remainder of the Euclidean division as common in mathematics, the % operator is not the modulo operator. It rather is called the remainder operator, whose result always has the same sign as the dividend. (In Haskell, the rem function does this).

This behaviour is pretty common amongst programming languages, notably also in C and Java from which the arithmetic conventions of JavaScript were inspired.

Solution 2:

Note that while in most languages, ‘%’ is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. For two values of the same sign, 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

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder

Post a Comment for "Javascript Modulo Operator Behaves Differently From Other Languages"