UNPKG

1.05 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { BigInt } from '@polkadot/x-bigint';
4import { assert } from "../assert.js";
5import { _0n, _1n, _2pow53n } from "./consts.js";
6import { nToBigInt } from "./toBigInt.js";
7
8const _sqrt2pow53n = BigInt(94906265);
9/**
10 * @name nSqrt
11 * @summary Calculates the integer square root of a bigint
12 */
13
14
15export function nSqrt(value) {
16 const n = nToBigInt(value);
17 assert(n >= _0n, 'square root of negative numbers is not supported'); // https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
18 // shortcut <= 2^53 - 1 to use the JS utils
19
20 if (n <= _2pow53n) {
21 return BigInt(Math.floor(Math.sqrt(Number(n))));
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
25
26 let x0 = _sqrt2pow53n;
27
28 while (true) {
29 const x1 = n / x0 + x0 >> _1n;
30
31 if (x0 === x1 || x0 === x1 - _1n) {
32 return x0;
33 }
34
35 x0 = x1;
36 }
37}
\No newline at end of file