如何找到Java BigInteger的平方根? [英] How can I find the Square Root of a Java BigInteger?
本文介绍了如何找到Java BigInteger的平方根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个库可以找到BigInteger的平方根?我希望它离线计算 - 只计算一次,而不是在任何循环内。所以即使是计算量很大的解决方案也没关系。
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 solution is okay.
我不想找到一些算法和实现。一个现成的解决方案将是完美的。
I don't want to find some algorithm and implement. A readily available solution will be perfect.
推荐答案
只是为了好玩:
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 BigInteger的平方根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文