JavaScript big integer square root
From here: https://golb.hplar.ch/2018/09/javascript-bigint.html
function sqrt(value) {
if (value < 0n) {
throw 'square root of negative numbers is not supported'
}
if (value < 2n) {
return value;
}
function newtonIteration(n, x0) {
const x1 = ((n / x0) + x0) >> 1n;
if (x0 === x1 || x0 === (x1 - 1n)) {
return x0;
}
return newtonIteration(n, x1);
}
return newtonIteration(value, 1n);
}
sqrt(BigInt(9))
There is an npm library bigint-isqrt, seem to work ok. It returns the floor value if there is no integer root.
const sqrt = require('bigint-isqrt');
> sqrt(1023n);
31n
> sqrt(1024n);
32n
Though it's still a mystery for me how magic numbers like value < 16n
and 1n << 52n
in it's implementation help finding a square root. Judging from a PR it's some sort of an approximation heuristic, I wonder whether it's more efficient than algorithms in other answers...
Here is more general solution for n-th root
function rootNth(val, k=2n) {
let o = 0n; // old approx value
let x = val;
let limit = 100;
while(x**k!==k && x!==o && --limit) {
o=x;
x = ((k-1n)*x + val/x**(k-1n))/k;
}
return x;
}
let v = 1000000n;
console.log(`root^3 form ${v.toString()} = ${rootNth(v,3n).toString()}` );