1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.bnSqrt = void 0;
|
4 | const bn_js_1 = require("./bn.js");
|
5 | const consts_js_1 = require("./consts.js");
|
6 | const toBn_js_1 = require("./toBn.js");
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function bnSqrt(value) {
|
21 | const n = (0, toBn_js_1.bnToBn)(value);
|
22 | if (n.isNeg()) {
|
23 | throw new Error('square root of negative numbers is not supported');
|
24 | }
|
25 |
|
26 |
|
27 | if (n.lte(consts_js_1.BN_MAX_INTEGER)) {
|
28 |
|
29 | return new bn_js_1.BN(~~Math.sqrt(n.toNumber()));
|
30 | }
|
31 |
|
32 |
|
33 | let x0 = consts_js_1.BN_SQRT_MAX_INTEGER.clone();
|
34 | while (true) {
|
35 | const x1 = n.div(x0).iadd(x0).ishrn(1);
|
36 | if (x0.eq(x1) || x0.eq(x1.sub(consts_js_1.BN_ONE))) {
|
37 | return x0;
|
38 | }
|
39 | x0 = x1;
|
40 | }
|
41 | }
|
42 | exports.bnSqrt = bnSqrt;
|