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

Add sqrt function. #277

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
16 changes: 16 additions & 0 deletions lib/bn.js
Original file line number Diff line number Diff line change
Expand Up @@ -2016,6 +2016,22 @@
return this.clone().imuln(num);
};

// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
BN.prototype.sqrt = function sqrt () {
var z = new BN(0);
if (this.gt(new BN(3))) {
z = this;
var x = this.div(new BN(2)).add(new BN(1));
while (x.lt(z)) {
z = x;
x = this.div(x).add(x).div(new BN(2));
}
} else if (!this.eq(new BN(0))) {
z = new BN(1);
}
return z;
};

// `this` * `this`
BN.prototype.sqr = function sqr () {
return this.mul(this);
Expand Down
9 changes: 9 additions & 0 deletions test/arithmetic-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,15 @@ describe('BN.js/Arithmetic', function () {
});
});

describe('.sqrt()', function () {
it('should raise number to the sqrt', function () {
var a = new BN('123456', 10);
var b = a.mul(a).sqrt();

assert.equal(b.toString(10), a.toString(10));
});
});

describe('.div()', function () {
it('should divide small numbers (<=26 bits)', function () {
assert.equal(new BN('256').div(new BN(10)).toString(10),
Expand Down