1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.bnSqrt = bnSqrt;
|
7 |
|
8 | var _assert = require("../assert");
|
9 |
|
10 | var _bn = require("./bn");
|
11 |
|
12 | var _consts = require("./consts");
|
13 |
|
14 | var _toBn = require("./toBn");
|
15 |
|
16 |
|
17 |
|
18 | const SQRT_MAX_SAFE_INTEGER = new _bn.BN(94906265);
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | function bnSqrt(value) {
|
34 | const n = (0, _toBn.bnToBn)(value);
|
35 | (0, _assert.assert)(n.gte(_consts.BN_ZERO), 'square root of negative numbers is not supported');
|
36 |
|
37 |
|
38 | if (n.lte(_consts.BN_MAX_INTEGER)) {
|
39 | return new _bn.BN(Math.floor(Math.sqrt(n.toNumber())));
|
40 | }
|
41 |
|
42 |
|
43 |
|
44 | let x0 = SQRT_MAX_SAFE_INTEGER.clone();
|
45 |
|
46 | while (true) {
|
47 | const x1 = n.div(x0).iadd(x0).ishrn(1);
|
48 |
|
49 | if (x0.eq(x1) || x0.eq(x1.sub(_consts.BN_ONE))) {
|
50 | return x0;
|
51 | }
|
52 |
|
53 | x0 = x1;
|
54 | }
|
55 | } |
\ | No newline at end of file |