【问题标题】:How to find the sqrt() for BigInteger in java? [duplicate]如何在 java 中找到 BigInteger 的 sqrt()? [复制]
【发布时间】:2018-12-22 07:49:48
【问题描述】:
import java.lang.*;
import java.math.*;

public class GFG {

    public static void main(String[] args) {

        // Creating a BigInteger object
        BigInteger big;

        big = new BigInteger("31739");

        BigInteger res  =big.sqrt();

        // print result
        System.out.println("Square root value of BigInteger " + big
        + " is " + res);
    }
}

BigInteger 中找不到符号sqrt() 请帮帮我!!!!!!

【问题讨论】:

  • 以上代码将在 Java 9 上运行。检查 Java9 文档中的 sqrt() 方法:docs.oracle.com/javase/9/docs/api/java/math/…
  • 没有一个答案似乎知道 Brent 和 Zimmermann 的 "Modern Computer Arithmetic" 的极快(特别是对于 256 位或更大的 BigIntegers)算法 1.12。尝试一下。我在我的 Delphi BigInteger 库中实现了它,它比这里显示的任何东西都要快。

标签: java biginteger sqrt


【解决方案1】:

此示例适用于 Java 9 或更高版本。对于以前的版本,您必须自己实现它:

public static BigInteger sqrt(BigInteger val) {
    BigInteger half = BigInteger.ZERO.setBit(val.bitLength() / 2);
    BigInteger cur = half;

    while (true) {
        BigInteger tmp = half.add(val.divide(half)).shiftRight(1);

        if (tmp.equals(half) || tmp.equals(cur))
            return tmp;

        cur = half;
        half = tmp;
    }
}

【讨论】:

    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多