javascript - 如何在 JavaScript 中提取 BigInt 的第 n 个根?
问题描述
如何在 JavaScript 中提取 BigInt 的第 n 个根?
Math.pow
不起作用。
解决方案
根据Dai 在评论中的建议,转换为 JavaScript 的 BigInt 表示法,基于Java中 BigInteger 的 Nth root 。确保传入的 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;
}
推荐阅读
- amazon-web-services - 如何使用 AWS CDK 从 EC2 Autoscaling Group 获取 EC2 ID 和私有 IP
- sqlite - 为其他列的每个不同值选择列的所有最大值
- python - 如何绘制 -log(x)?
- python - 为什么我在 Python Pandas dtype float64 上出现错误?
- ssl-certificate - 配置 SSL 证书时产生 vsftpd 服务器错误的原因是什么?
- firebase - 如何在 Firebase 函数中使用 FCM
- python - 您对使用 MobileNet 进行自定义尺寸图像有什么想法吗?
- haskell - 如何否定列表中除特定数字之外的每个数字?哈斯克尔
- java - 将所有背景颜色放入此 XML - Android
- python - python中的变量没有被更新