如何在 JavaScript 中提取 BigInt 的 n 次方根?
Math.pow
不起作用。
最佳答案
转换为 JavaScript 的 BigInt 表示法,基于 Nth root of BigInteger正如 Dai 在评论中建议的那样,来自 Java。确保传入的 base 和 root 是 BigInt 的,如果不是,则可以为两个输入设置 base = BigInt(base);
等。这是基于牛顿公式。此外,BigInt 不能表示小数,因此每个除法都是取整除法,因此这不适用于 16 的立方根。以下是一些值得一读的 BigInt Mozilla 文档: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;
}
关于javascript - 如何在 JavaScript 中提取 BigInt 的 n 次方根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64190185/