如何在Java中找到BigInteger的sqrt()?

时间:2018-12-22 07:49:49

标签: java biginteger sqrt

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);
    }
}

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

enter image description here

1 个答案:

答案 0 :(得分:0)

此示例在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;
    }
}