JavaScript big integer square root

一曲冷凌霜 提交于 2019-12-23 11:59:22

问题


This concerns the new JavaScript BigInt type, as supported in Chrome and Node v10.4

Both the following lines throw an error:

Math.sqrt(9n)
Math.sqrt(BigInt(9))

Error is:

Cannot convert a BigInt value to a number

How do I get the square root of a BigInt in JavaScript? TIA


回答1:


From here: 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))



回答2:


Here is more general solution for n-th root

function rootNth(val, k=2n) {
    let o=0; // old approx value
    let x = val;
    let limit = 100;
    
    while(x**k!=k && x!=o && --limit) {
      o=x;
      x = ((k-1n)*x + val/x**(k-1n))/k;
    }
    
    return x;
}

let v = 1000000n;
console.log(`root^3 form ${v.toString()} = ${rootNth(v,3n).toString()}` );


来源:https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!