JAVA语言isPrime关键词_Java Guava IntMath isPrime()用法及代码示例

这篇博客介绍了Guava库中IntMath类的isPrime(int n)方法,该方法用于判断给定的整数是否为质数。如果数字大于1且只能被1和自身整除,则认为它是质数。文章通过示例代码展示了如何使用这个方法,并指出当传入负数时,方法会抛出IllegalArgumentException。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值