给定若干个正整数,请判断素数的个数用java编写

如题所述

第1个回答  2014-03-25
public class Hello{
public static void main(String[] args){
int[] arr = {1,2,43,3,5,65,7,56,7,2,4,6};
int shu = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] % 2 == 0){
++shu;
}
}
System.out.println("素数的个数为:" + shu);
}
}

本回答被网友采纳
第2个回答  2014-03-25

试试下面的代码:

public class Test {
    public static void main(String[] args){
        int[] sushuArray = new int[]{3,6,4,13,7,5,4};
        int count = 0;
        for(int i : sushuArray){
            if(sushu(i)){
                count++;
            }
        }
        System.out.println("素数个数为:"+count+"个");
    }
    
    private static boolean sushu(int a){
        for(int i=2; i<a; i++){
            if(a%i == 0){
                return false;
            }
        }
        return true;
    }
}

第3个回答  2014-03-25
看下思想就ok了,下面是我开始学编程的时候做的。看一下你就会明白的。

for example:

判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。
public class lianxi02 {
public static void main(String[] args) {
int count = 0;
for(int i=101; i<200; i+=2) {
boolean b = false;
for(int j=2; j<=Math.sqrt(i); j++)
{
if(i % j == 0) { b = false; break; }
else { b = true; }
}
if(b == true) {count++;System.out.println(i );}
}
System.out.println( "素数个数是: " + count);
}
}
相似回答