【问题标题】:javascript how to multiply BigInt ** 0.5?javascript如何乘以BigInt ** 0.5?
【发布时间】:2021-07-25 00:05:24
【问题描述】:

我正在将 python 代码转换为 js,但无法解决这个问题 x = int(num ** 0.5) (num 是大整数)

如何在 javascript BigInt 中计算?

谢谢我解决了

var num = BigInt("14564566644656456665555555555555555555555555545654645"); //example
num = BigInt(Math.round(parseInt(num.toString()) ** 0.5 )); // result is exact same as python tested more 

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用bignumber.js 完成此操作。您需要将 BigInt 转换为 BigNumber,计算平方根 (sqrt),然后使用 toFixed 将其四舍五入为整数:

function sqrt( x ) {
  return BigInt( BigNumber( x ).sqrt().toFixed(0) );
}

console.log( sqrt( 14564566644656456665555555555555555555555555545654645n ).toString() );
<script src="https://unpkg.com/bignumber.js@9.0.1/bignumber.min.js"></script>

您当前在 JavaScript 和 Python 中的解决方案已取消 1897074225,因为您正在转换为浮点数学,这对于您正在使用的 BigInt 来说没有足够的精度。 Is floating point math broken?

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2013-08-21
    • 2015-11-21
    • 2011-02-11
    • 2020-02-13
    相关资源
    最近更新 更多