How can I find the Square Root of a Java BigInteger?

后端 未结 19 1112
[愿得一人]
[愿得一人] 2020-11-28 08:10

Is there a library that will find the square root of a BigInteger? I want it computed offline - only once, and not inside any loop. So even computationally expensive solutio

19条回答
  •  遥遥无期
    2020-11-28 08:23

    Strange that nobody has mentioned it earlier but in java 9 you have sqrt in BigInteger, so you can just use it like that:

    BigInteger nine = BigInteger.valueOf(9);
    BigInteger three = nine.sqrt();
    

    https://docs.oracle.com/javase/9/docs/api/java/math/BigInteger.html#sqrt--


    EDIT-1

    Adding that there is another flavour of this function that, in addition to the floored square root, also returns the remainder.

    sqrtAndRemainder() BigInteger[]
    
    Returns an array of two BigIntegers containing the integer square root s
    of this and its remainder this - s*s, respectively.
    

提交回复
热议问题