diff --git a/README.md b/README.md index 0443551..6b9b949 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ either `le` (little-endian) or `be` (big-endian). * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) -* `a.pow(b)` - raise `a` to the power of `b` +* `a.pow(b)` - raise `a` to the power of `b` (`i`) * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divRound(b)` - rounded division diff --git a/lib/bn.js b/lib/bn.js index a3e2b15..2658a4b 100644 --- a/lib/bn.js +++ b/lib/bn.js @@ -1919,25 +1919,32 @@ }; // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { + BN.prototype.ipow = function ipow (num) { var w = toBitArray(num); - if (w.length === 0) return new BN(1); + if (w.length === 0) { + this.words[0] = 1; + this.length = 1; + return this; + } // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { + for (var i = 0; i < w.length; i++, this.isqr()) { if (w[i] !== 0) break; } if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + for (var q = this.sqr(); i < w.length; i++, q.isqr()) { if (w[i] === 0) continue; - res = res.mul(q); + this.imul(q); } } - return res; + return this; + }; + + BN.prototype.pow = function pow (num) { + return this.clone().ipow(num); }; // Shift-left in-place diff --git a/test/arithmetic-test.js b/test/arithmetic-test.js index ae39a85..8fc6122 100644 --- a/test/arithmetic-test.js +++ b/test/arithmetic-test.js @@ -282,6 +282,22 @@ describe('BN.js/Arithmetic', function () { assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); }); + it('0 power should equal to 1', function () { + assert.equal(new BN(123).pow(new BN(0)).toNumber(), 1); + }); + }); + + describe('.ipow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + a.ipow(b); + + assert.equal(a.toString(16), '15963da06977df51909c9ba5b'); + }); + it('0 power should equal to 1', function () { + assert.equal(new BN(123).ipow(new BN(0)).toNumber(), 1); + }); }); describe('.div()', function () {