这涉及到新的javascript bigint类型,如chrome和node v10.4中所支持的那样。
以下两行都会引发错误:
Math.sqrt(9n) Math.sqrt(BigInt(9))
错误是:
无法将bigint值转换为数字
如何在javascript中得到bigint的平方根?蒂亚
从这里开始: https://golb.hplar.ch/2018/09/javascript-bigint.html
function sqrt(value) { if (value < 0n) { throw 'square root of negative numbers is not supported' } if (value < 2n) { return value; } function newtonIteration(n, x0) { const x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) { return x0; } return newtonIteration(n, x1); } return newtonIteration(value, 1n); } sqrt(BigInt(9))