📜  Java番石榴 | IntMath 类的 isPrime() 方法

📅  最后修改于: 2022-05-13 01:55:48.321000             🧑  作者: Mango

Java番石榴 | IntMath 类的 isPrime() 方法

Guava 的 IntMath 类的 isPrime (int n)方法用于检查传递给它的参数是否为素数。如果传递给它的参数是素数,则返回 True,否则返回 False。

如果一个数只能被 1 和该数本身整除,则称该数为数。

句法 :

public static boolean isPrime(int n)

参数:该方法只接受一个参数n ,它是整数类型并且要检查素数。

返回值:

  • true :如果 n 是素数。
  • false :如果 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

参考 :
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#isPrime-int-