UNPKG

1.21 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.nSqrt = void 0;
4const x_bigint_1 = require("@polkadot/x-bigint");
5const consts_js_1 = require("./consts.js");
6const toBigInt_js_1 = require("./toBigInt.js");
7/**
8 * @name nSqrt
9 * @summary Calculates the integer square root of a bigint
10 */
11function nSqrt(value) {
12 const n = (0, toBigInt_js_1.nToBigInt)(value);
13 if (n < consts_js_1._0n) {
14 throw new Error('square root of negative numbers is not supported');
15 }
16 // https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
17 // shortcut <= 2^53 - 1 to use the JS utils
18 if (n <= consts_js_1._2pow53n) {
19 // ~~ is more performant that Math.floor
20 return (0, x_bigint_1.BigInt)(~~Math.sqrt(Number(n)));
21 }
22 // Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
23 // output will be larger than this, we expect this to be a safe start
24 let x0 = consts_js_1._sqrt2pow53n;
25 while (true) {
26 const x1 = ((n / x0) + x0) >> consts_js_1._1n;
27 if (x0 === x1 || (x0 === (x1 - consts_js_1._1n))) {
28 return x0;
29 }
30 x0 = x1;
31 }
32}
33exports.nSqrt = nSqrt;