![](/img/trans.png)
[英]Performance Improvement For Using BigInteger While Calculating Square Root
[英]Understanding underlying logic/maths for calculating BigInteger square root in Java
我想用Java計算BigInteger的平方根。 在調查過程中,我發現了這個很棒的鏈接。 如何找到Java BigInteger的平方根? ,之前在StackOverflow上問過。
有兩個很棒的代碼片段可以解決此問題。 但是缺少基本的邏輯或數學。
這是第一個 :
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);
}
從這里帶走的。
這是第二個:
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回答。
任何人都可以為主題的完整性而解釋或指向基礎數學或邏輯。
兩者基本上都是牛頓迭代 。
但是,第一個代碼段有一些奇怪的變化,因此我將選擇第二個代碼段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.