Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript big integer square root

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

like image 590
danday74 Avatar asked Dec 08 '18 15:12

danday74


People also ask

How do you take the square root of a BigInteger in Java?

sqrt() is an inbuilt function added in Java SE 9 & JDK 9 which returns BigInteger value of square root of a BigInteger on which sqrt() method is applied. It is the same as the floor(sqrt(n)) where n is a number.

How do you code a square root in JavaScript?

To find the square root of a number in JavaScript, you can use the built-in Math. sqrt() method.

Does JavaScript support BigInt?

JavaScript provides two library functions for representing BigInt values as signed or unsigned integers: BigInt. asUintN(width, BigInt) : wraps a BigInt between 0 and 2width-1. BigInt.

How do you take a long square root in Java?

Java sqrt() method with Examplessqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity.


1 Answers

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))
like image 90
kopaty4 Avatar answered Sep 17 '22 18:09

kopaty4