Javascript Modular Arithmetic

Javascript evaluates the following code snippet to -1.

  -5% 4

I understand that the remainder theorem states a = bq + r such that 0 & le; r <b Given the above definition, the answer should not be 3? Why does JavaScript return -1?

+6
source share
5 answers

Because it is the remainder operator , not modulo. But there is an offer for the right one .

Quote from Ecma 5.1

the remainder r of the dividend is n, and the divisor d is determined 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

+6
source

The reason is that % not a module, but a remainder operator. Look here

+1
source

If you use % for modular arithmetic, it does not matter (at least conceptually): -5 % 4 evaluates to -1 or 3, because these two numbers are congruent modulo 4: for the purposes of modular arithmetic, they are the same.

0
source

Most programming languages ​​use a symmetric module, which differs from the mathematical one for negative values.

The mathematical module can be calculated using symmetric modulo as follows:

 a mod b = ((a % b) + b) % b 

mod math modulo

% symmetric modulo

0
source

... if the remainder is non-zero, there are two possible options for the remainder: one negative and the other positive, and there are two possible options for the quotient. Usually in number theory, a positive remainder is always chosen, but programming languages ​​are chosen depending on the language and the signs a and n. ( http://en.wikipedia.org/wiki/Modulo_operation )

in python that takes a divisor sign:

  -5 % 4 == 3 # -5 = (-2) * 4 + 3 

in javascript that takes a divident sign:

  -5 % 4 == -1 # -5 = (-1) * 4 - 1 
-1
source

Source: https://habr.com/ru/post/974981/


All Articles