Java BigInteger sqrt()方法
java.math.BigInteger.sqrt() 是 Java SE 9和JDK 9中加入的 一个内置函数,它可以返回应用sqrt()方法的BigInteger的平方根值。它与floor(sqrt(n))相同,其中n是一个数字。如果实数的平方根不能以积分形式表示,那么这个平方根就小于实数的平方根。
语法
public BigInteger sqrt()
参数: 该方法不接受任何参数。
返回值: 该方法返回该BigInteger的整数平方根。
异常: 如果BigInteger为负数,该方法将抛出ArithmeticException。
例子
输入 : 234876543456
输出 : 484640
解释 : 122的输入是大整数。
122的平方根是11.04536
其BigInteger等价物为11,使用BigInteger类的sqrt()
的方法,我们可以得到
任何BigInteger的平方根。
输入 : 122
输出 : 11
下面的程序说明了BigInteger类的sqrt()方法。
程序1: 展示sqrt()方法的应用,以获得31739的平方根。
// Please run this program in JDK 9 or JDK 10
// Java program to demonstrate sqrt() method
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating a BigInteger object
BigInteger big, squareRoot;
big = new BigInteger("31739");
// calculate square root o bigInteger
// using sqrt() method
squareRoot = big.sqrt();
// print result
System.out.println("Square root value of BigInteger " + big
+ " is " + squareRoot);
}
}
输出
Square root value of BigInteger 31739 is 178
程序2: 显示sqrt()方法抛出的异常。
//Please run this program in JDK 9 or JDK 10
// Java program to demonstrate sqrt() method
//and exception thrown by it
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating a BigInteger object
BigInteger big,squareRoot=null;
big = new BigInteger("-2345");
//calculate square root o bigInteger
//using sqrt() method
try {
squareRoot = big.sqrt();
} catch (Exception e) {
e.printStackTrace();
}
// print result
System.out.println("Square root value of BigInteger " + big
+" is "+squareRoot);
}
}
输出
java.lang.ArithmeticException: Negative BigInteger
at java.base/java.math.BigInteger.sqrt(Unknown Source)
at GFG.main(GFG.java:19)
Square root value of BigInteger -2345 is null
参考资料: https://docs.oracle.com/javase/9/docs/api/java/math/BigInteger.html#sqrt-