2

How do I extract the nth root of a BigInt in JavaScript?

Math.pow doesn't work.

2

1 Answer 1

3

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; } 
Sign up to request clarification or add additional context in comments.

9 Comments

Huh... TIL that ** is a valid operator in JavaScript! - and it is defined for number and BigInt.
** is the Exponentiation operator...
Yup! It works in Python too and I also think Java but I'm not sure. I was a little confused when I was translating this to JavaScript because of the weird naming conventions of the pseudo code, but I was able to figure out that in the original pseudo code, the first number was actually the root and the second number was the base, so I switched it around in this solution to make more sense, like how Math.pow() works.
BTW, it might be an idea to add a type-check to 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.
@Samathingamajig Man, that is incredibly stupid IMO. ** is WAY more concise. Concise code is better code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.