public class Prime { public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 2; i <= 10000; i++) {
for (int j = 2; j <= (int) Math.sqrt(i) + 1; j++) { if (i == 2 && j == 2) {
System.out.print(i + " ");
continue;
} if (i % j == 0) {
break;
}
if (j >= (int) Math.sqrt(i) + 1) {
System.out.print(i + " ");
}
}
}
System.out.println();
long end = System.currentTimeMillis();
System.out.println("time : " + (end - start) + " milliseconds");
}
}这个地方:
if (j >= (int) Math.sqrt(i) + 1) {
System.out.print(i + " ");
}
为什么还要判断一次呢?谢谢!

解决方案 »

  1.   

                   if (j >= (int) Math.sqrt(i) + 1) {
                        //System.out.print(i + " ");
                    }
                    else
                    {
                        System.out.print(i + " ");
                    }
    这样弄一下,发现要是不判断他就把除不尽的数都列出来了
      

  2.   

    public class Sushu { /**
     * @param args
     */

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Sushu s=new Sushu();
    boolean b=s.sushu(110);
    System.out.println("验证素数:"+b);
    }
      
    public boolean sushu(int num){
    boolean flag=false;
    if(num!=0&&num!=1&&num>2){
            int t=num/2+1;
    for(int i=2;i<=t;i++){
    if(num%i!=0){
    flag=true;
    }else{
    flag=false;
    break;
    }

    }

    }else if(num==2){
    flag=true;
    }else{
    flag=false;
    }
    return flag;

    }
    }