peterolson / BigInteger.js

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

Invalid modInv result for -486 and 217 ? #197

Closed EricGrange closed 4 years ago

EricGrange commented 4 years ago

With version 1.6.47 (from cdnjs) when computing modInv for -486 and 217, the returned value is -96, while it should be 121

https://jsbin.com/febiheqeja/edit?html,js,output

I found the test case in https://rosettacode.org/wiki/Modular_inverse and cross-tested with MPIR and Wolfram alpha's widget (https://www.wolframalpha.com/widgets/view.jsp?id=a9d64f006accc458a887ceb71eca63c6)

EricGrange commented 4 years ago

PSD: I ran the test in Chrome 77

peterolson commented 4 years ago

If the first argument is negative, the result will be negative, matching the native JavaScript modulo operator.

Note that it's easy to make the result positive if it's required for your purposes: 121 = 217 - 96

EricGrange commented 4 years ago

Good for me, thanks for detailing the rationale!