【问题标题】:Understanding underlying logic/maths for calculating BigInteger square root in Java了解在 Java 中计算 BigInteger 平方根的底层逻辑/数学
【发布时间】: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


【解决方案1】:

两者基本上都是newton iteration

但是第一个代码 sn-p 有一些奇怪的转折,所以我会选择第二个 sn-p。

【讨论】:

  • 谢谢我理解了迭代规则,第二个代码似乎更明显。但我不明白BigInteger div = BigInteger.ZERO.setBit(x.bitLength()/2); 行在做什么?是设置div=1吗?
  • 它在平方根附近为迭代创建一个起点,即通过在该位置设置一个位来将x的长度减半。
  • 长度的一半,字面上的还是数学上的?
  • (二进制)位数的一半。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 2011-05-23
  • 1970-01-01
相关资源
最近更新 更多