JAVA编程 判断素数

来源:百度知道 编辑:UC知道 时间:2024/05/26 20:57:22
用Math类的随机函数产生10个2~100的正整数,然后逐个判断这10个数是不是素数。并输出判断的结果

public class Test {

public static final int X=2;
public static final int Y=100;
/**
* 用Math类的随机函数产生10个2~100的正整数,然后逐个判断这10个数是不是素数。并输出判断的结果
* @param args
*/
public static void main(String[] args) {
int[] n=new int[10]; //定义一个长度为10的整型数组
for(int i=0;i<n.length;i++){
n[i]=(int) (Math.random()*1000/(Y-X))+X; //给数组元素赋值,值为2~100的正整数
boolean b=true;
for(int j=2;j<=Math.sqrt(n[i]);j++){ //判断是否为素数
if( n[i]%j==0){
b=false;
System.out.println("a["+i+"]="+n[i]+"不是素数!");
}
}
if(b){
System.out.println("a["+i+"]="+n[i]+"是素数!");
}
}

}

}