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

后端 未结 19 1113
[愿得一人]
[愿得一人] 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:17

    This is the best (and shortest) working solution I've found

    http://faruk.akgul.org/blog/javas-missing-algorithm-biginteger-sqrt/

    Here is the code:

      public static BigInteger sqrt(BigInteger n) {
        BigInteger a = BigInteger.ONE;
        BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString());
        while(b.compareTo(a) >= 0) {
          BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
          if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE);
          else a = mid.add(BigInteger.ONE);
        }
        return a.subtract(BigInteger.ONE);
      }
    

    I've tested it and it's working correctly (and seems fast)

提交回复
热议问题