Guava IntMath類的isPrime(int n)方法用於檢查傳遞給它的參數是否為質數。如果傳遞給它的參數為質數,則返回True,否則返回False。
如果數字隻能被1和數字本身整除,則稱該數字為質數。
用法:
public static boolean isPrime(int n)
參數:該方法僅接受一個整數類型的參數n,並將對其進行素數檢查。
返回值:
- 真正:如果n是素數。
- 假:如果n為0、1或複合數字。
異常:如果n為負數,則方法isPrime(int n)拋出IllegalArgumentException。
範例1:
// Java code to show implementation of
// isPrime(int n) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int a1 = 63;
// Using isPrime(int n)
// method of Guava's IntMath class
if(IntMath.isPrime(a1))
System.out.println(a1 + " is a prime number");
else
System.out.println(a1 + " is not a prime number");
int a2 = 17;
// Using isPrime(int n)
// method of Guava's IntMath class
if(IntMath.isPrime(a2))
System.out.println(a2 + " is a prime number");
else
System.out.println(a2 + " is not a prime number");
}
}
輸出:
63 is not a prime number 17 is a prime number
範例2:
// Java code to show implementation of
// isPrime(int n) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static boolean findPrime(int n)
{
try {
// Using isPrime(int n) method
// of Guava's IntMath class
// This should throw "IllegalArgumentException"
// as n is negative
boolean ans = IntMath.isPrime(n);
// Return the answer
return ans;
}
catch (Exception e) {
System.out.println(e);
return false;
}
}
// Driver code
public static void main(String args[])
{
int a1 = -7;
try {
// Using isPrime(int n) method
// of Guava's IntMath class
// This should throw "IllegalArgumentException"
// as a1 is negative
findPrime(a1);
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
java.lang.IllegalArgumentException:n (-7) must be >= 0
相關用法
- Java Guava IntMath gcd(int a, int b)用法及代碼示例
- Java Guava IntMath mean()用法及代碼示例
- Java Guava IntMath mod()用法及代碼示例
- Java Guava IntMath pow(int b, int k)用法及代碼示例
- Java Guava IntMath floorPowerOfTwo()用法及代碼示例
- Java Guava IntMath ceilingPowerOfTwo()用法及代碼示例
- Java Guava IntMath isPowerOfTwo()用法及代碼示例
- Java Guava IntMath binomial()用法及代碼示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代碼示例
- Java IntMath.checkedPow(int b, int k)用法及代碼示例
- Java IntMath.checkedAdd(int a, int b)用法及代碼示例
- Java IntMath.checkedSubtract(int a, int b)用法及代碼示例
- Java IntMath.checkedMultiply(int a, int b)用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 Java Guava | isPrime() method of IntMath Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。