peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

Modulo function incorrect for negative numbers #213

Closed campbellgalon closed 3 years ago

campbellgalon commented 3 years ago

Consider the following expressions: -4 % 10 = 6 4 % -10 = -6

bigInt(-4).mod(bigInt(10)).value --> -4 bigInt(4).mod(bigInt(-10)).value --> 4

Could be fixed by checking if either operand in your modulo function is negative, and if so, returning the current result plus the second operand

peterolson commented 3 years ago

This is working as expected. As stated in the documentation:

The sign of the remainder will match the sign of the dividend.

This is the same way that modulo is calculated in native JavaScript. Type evaluating -4 % 10 and 4 % -10 in a JavaScript console.