Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bn: introduce in-place pow, .ipow() [WIP] #121

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 14 additions & 7 deletions lib/bn.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test/arithmetic-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down