peterolson / BigInteger.js

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

Enhancement. Fast mulmod method #148

Closed username1565 closed 6 years ago

username1565 commented 6 years ago

Hello, Peter Olson! Can you add in your free time, fast multiply mod method, aka Montgomery trick: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication

You can see source code here: https://github.com/indutny/bn.js/blob/master/lib/bn.js function BN.mont() and rewrite this for your bigInt-library.

username1565 commented 6 years ago

Also, this is available, here, in the peercoin paperwallet: https://github.com/Elbandi/peercoin-walletgenerator/blob/master/src/biginteger.js

gardhr commented 6 years ago

You're overoptimizing.

screenshot from 2018-07-09 05-33-00

Just need a faster machine!

username1565 commented 6 years ago

What do you mean in picture? Mulmod is not multiple or square function. This is fast method for multiple and mod then. In many bigInteger libraries this function is named as mulmod ("x*x%n") As you can see by last link at line 1179, there is many functions:

//1. Montgomery reduction
function Montgomery(m){/*code*/}
//2. xR mod m
Montgomery.prototype.convert = function (x) {/*code*/}
//3. x/R mod m
Montgomery.prototype.revert = function (x) {/*code*/}
//4. x = x/R mod m (HAC 14.32)
Montgomery.prototype.reduce = function (x) {/*code*/}
//5. r = "xy/R mod m"; x,y != r
Montgomery.prototype.mulTo = function (x, y, r) {/*code*/}
//r = "x^2/R mod m"; x != r
Montgomery.prototype.sqrTo = function (x, r) {/*code*/}

Also, you can see there Barrett modular reduction, (at line 1241) and Modular reduction using "classic" algorithm, (at line 1164)

peterolson commented 6 years ago

BigInteger.js is not designed to be a fully-featured number theory library. A very small percentage of the users of this library would ever use a mulMod function, so I probably won't be adding this.