是否有可以找到 BigInteger 平方根的库?我希望它离线计算 - 只计算一次,而不是在任何循环内。所以即使是计算昂贵的解决方案也可以。
我不想找到一些算法并实现。一个现成的解决方案将是完美的。
最佳答案
只是为了好玩:
public static BigInteger sqrt(BigInteger x) {
BigInteger div = BigInteger.ZERO.setBit(x.bitLength()/2);
BigInteger div2 = div;
// Loop until we hit the same value twice in a row, or wind
// up alternating.
for(;;) {
BigInteger y = div.add(x.divide(div)).shiftRight(1);
if (y.equals(div) || y.equals(div2))
return y;
div2 = div;
div = y;
}
}
关于java - 如何找到 Java BigInteger 的平方根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4407839/