Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ≤ r < b. Given the definition above should the answer not be 3? Why does JavaScript return -1?

like image 476
walkerrandophsmith Avatar asked Sep 08 '14 14:09

walkerrandophsmith


2 Answers

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

like image 94
nullpotent Avatar answered Sep 30 '22 03:09

nullpotent


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

like image 37
niklassc Avatar answered Sep 30 '22 02:09

niklassc