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; } base and root and throwing an exception if the types aren't actual bigint values because I think this function may still run (but not produce a useful result) if non-bigint values are provided. I've edited the answer to add that check. This also means the function will fail when used in a JS environment without BigInt, like Internet Explorer or wscript/cscript.** is WAY more concise. Concise code is better code.