首页 > 解决方案 > 如何在 JavaScript 中提取 BigInt 的第 n 个根?

问题描述

如何在 JavaScript 中提取 BigInt 的第 n 个根?

Math.pow不起作用。

标签: javascriptbiginteger

解决方案


根据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;
}

推荐阅读