【发布时间】:2015-10-24 04:42:42
【问题描述】:
我想在 Java 中计算 BigInteger 的平方根。在调查时,我发现了这个很棒的链接 How can I find the Square Root of a Java BigInteger?,之前在 StackOverflow 上问过。
有两个很棒的代码 sn-ps 可以解决这个问题。但是缺少基本的逻辑或数学。
这是第一个:
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);
}
取自here。
这是第二个:
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;
}
}
由@EdwardFalk 回答。
为了主题的完整性,任何人都可以解释或指出基本的数学或逻辑。
【问题讨论】:
标签: java biginteger square-root