1 | import { BigInt } from '@polkadot/x-bigint';
|
2 | import { _0n, _1n, _2pow53n, _sqrt2pow53n } from './consts.js';
|
3 | import { nToBigInt } from './toBigInt.js';
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | export function nSqrt(value) {
|
9 | const n = nToBigInt(value);
|
10 | if (n < _0n) {
|
11 | throw new Error('square root of negative numbers is not supported');
|
12 | }
|
13 |
|
14 |
|
15 | if (n <= _2pow53n) {
|
16 |
|
17 | return BigInt(~~Math.sqrt(Number(n)));
|
18 | }
|
19 |
|
20 |
|
21 | let x0 = _sqrt2pow53n;
|
22 | while (true) {
|
23 | const x1 = ((n / x0) + x0) >> _1n;
|
24 | if (x0 === x1 || (x0 === (x1 - _1n))) {
|
25 | return x0;
|
26 | }
|
27 | x0 = x1;
|
28 | }
|
29 | }
|