素数
素数(prime number)又称质数,有无限多个。质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。
接下来通过代码判断一个自然数是否素数:
package com.itszt.test8;
/**
* 素数
*/
public class Test5 {
public static void main(String[] args) {
judge(127);
}
static void judge(int n){
if(n<=1){
System.out.println("无效数据!");
return;
}
if(n%2==0 || n%3==0){
System.out.println(n+" 不是素数");
}else{
System.out.println(n+" 是素数");
}
}
}
运行上述代码,结果如下:
127 是素数