当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Guava IntMath isPrime()用法及代码示例


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

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



相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 Java Guava | isPrime() method of IntMath Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。