How do I extract the nth root of a BigInt in JavaScript?
Math.pow
doesn't work.
How do I extract the nth root of a BigInt in JavaScript?
Math.pow
doesn't work.
Converted to JavaScript's BigInt notation, based off of Nth root of BigInteger from Java as suggested by Dai in the comments. Make sure that base and root that are passed in are BigInt's, if not then you can just set base = BigInt(base);
etc. for the two inputs. This is based off of Newton's formula. Also, BigInt's can't represent decimals, so every division is floored division so this doesn't work for the cube root of 16, for example. Here's some Mozilla documentation of BigInt that is worth the read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
function iroot(base, root) {
if (typeof base !== 'bigint' || typeof root !== 'bigint') throw new Error("Arguments must be bigints.");
let s = base + 1n;
let k1 = root - 1n;
let u = base;
while (u < s) {
s = u;
u = ((u*k1) + base / (u ** k1)) / root;
}
return s;
}