了解Java中计算BigInteger平方根的基本逻辑/数学
我想在Java中计算BigInteger的平方根。在调查过程中,我发现了这个很棒的链接,在StackOverflow的早些时候被问到 这里给出了两个很好的代码片段来解决这个问题。但根本的逻辑或数学是不存在的 这是第一个:了解Java中计算BigInteger平方根的基本逻辑/数学,java,biginteger,square-root,Java,Biginteger,Square Root,我想在Java中计算BigInteger的平方根。在调查过程中,我发现了这个很棒的链接,在StackOverflow的早些时候被问到 这里给出了两个很好的代码片段来解决这个问题。但根本的逻辑或数学是不存在的 这是第一个: BigInteger sqrt(BigInteger n) { BigInteger a = BigInteger.ONE; BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).t
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回答
为了主题的完整性,请任何人解释或指出基本的数学或逻辑。两者基本上都是一个概念
但是,第一个代码段有一些奇怪的曲折,所以我会选择第二个代码段。谢谢,我理解了迭代规则,第二个代码看起来更明显。但是我不明白这行是什么
biginger div=biginger.ZERO.setBit(x.bitLength()/2)代码>正在做什么?它是否设置了div=1
?它为迭代创建了一个接近平方根的起点,即一个数字通过在此位置设置一个位将x
的长度减半。长度的一半,从字面上或数学上讲,是(二进制)位数的一半。