1 |
|
2 |
|
3 | import { BigInt } from '@polkadot/x-bigint';
|
4 | import { assert } from "../assert.js";
|
5 | import { _0n, _1n, _2pow53n } from "./consts.js";
|
6 | import { nToBigInt } from "./toBigInt.js";
|
7 |
|
8 | const _sqrt2pow53n = BigInt(94906265);
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export function nSqrt(value) {
|
16 | const n = nToBigInt(value);
|
17 | assert(n >= _0n, 'square root of negative numbers is not supported');
|
18 |
|
19 |
|
20 | if (n <= _2pow53n) {
|
21 | return BigInt(Math.floor(Math.sqrt(Number(n))));
|
22 | }
|
23 |
|
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 |