java.math.BigInteger.byteValueExact()是Java SE 9和JDK 9中添加的一個內置函數,該函數返回應用了sqrt()方法的BigInteger平方根的BigInteger值。它與floor(sqrt(n))相同,其中n是一個數字。如果不能將實平方根表示為整數值,則此平方根小於實平方根。
用法:
public BigInteger sqrt()
參數:該方法不帶任何參數。
返回值:方法返回此BigInteger的整數平方根。
異常:如果BigInteger為負,則該方法將引發ArithmeticException。
例:
Input: 234876543456 Output: 484640 Explanation: 122 is given as input which is the bigInteger. The square root of 122 is 11.04536 whose BigInteger equivalent is 11 and using sqrt() method of BigInteger class we can get Square root of any BigInteger. Input: 122 Output: 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–
相關用法
- Java sqrt()用法及代碼示例
- Java StrictMath sqrt()用法及代碼示例
- Java BigDecimal sqrt()用法及代碼示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代碼示例
- Java BigInteger pow()用法及代碼示例
- Java BigInteger xor()用法及代碼示例
- Java BigInteger or()用法及代碼示例
- Java BigInteger mod()用法及代碼示例
- Java BigInteger and()用法及代碼示例
- Java BigInteger not()用法及代碼示例
- Java BigInteger abs()用法及代碼示例
- Java BigInteger setBit()用法及代碼示例
- Java BigInteger testBit()用法及代碼示例
- Java BigInteger toString()用法及代碼示例
- Java BigInteger intValue()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 BigInteger sqrt() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。