peterolson / BigInteger.js

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

modular inverse function #62

Closed yvesago closed 8 years ago

yvesago commented 8 years ago

A modular inverse function could be a good addons for cryptographic applications Here one sample code inspired from C sample in http://rosettacode.org/wiki/Modular_inverse

function _invmod( a, n ) {
  var t = bigInt('0'); var nt = bigInt('1');
  var r = n; var nr = a.mod(n);
  var tmp;
  while (! nr.isZero() ) {
    var quot = r.divide(nr);
    tmp = nt;  nt = t.subtract(quot.multiply(nt));  t = tmp;
    tmp = nr;  nr = r.subtract(quot.multiply(nr));  r = tmp;
  };
  if ( r.greater(1) ) return bigInt(0);
  if ( t.isNegative() ) t = t.add(n);
  return t;
}
peterolson commented 8 years ago

I feel like it would be better to make a separate library extending BigInteger.js for number theory algorithms like this. There are lots of functions that could be added at the expense of bloating the library, and I don't want the library to become a kitchen sink of random functions, beyond what it already is. A while back when this was more of my toy project than something I expected people to use, I added features that aren't useful to many people like negative and unary base conversion, and I only really keep them to maintain backwards compatibility.

I don't see this particular function being used very often, since most programmers aren't even aware of this function or how it is useful, and those who are could likely implement the function themselves without too much trouble.