用java实现输出0-200之间的质数,每行输出6个。 
下面是我的代码,请高手指教 
int n=0; int i=0; 
outer:for(i=0;i<=200;i++) 

if(i%7==0&&i%4!=0) 
continue outer; 

System.out.print(" "+i); 
n++; 
if(n<5) 
continue; 
System.out.println(); 
n=0; 

}

解决方案 »

  1.   

    请参考,你的代码不能运行,而且算法有问题!package test;public class TestZhiShu {
      public static void main(String[] args) {
        int n = 1;
        int i = 0;
        System.out.print("   " + 2);
        for (i = 3; i <= 200; i += 2) {
          if (isprime(i)) {
            System.out.print("   " + i);
            n++;
            if (n < 6)
              continue;
            System.out.println();
            n = 0;
          }
        }
      }  public static boolean isprime(int x) {
        for (int i = 2; i <= Math.sqrt(x); i++) {
          if (x % i == 0)
            return false;
        }
        return true;
      }
    }
      

  2.   

    补充一个高效的判断是否为质数的方法,比前一个快5-10倍
      public static boolean isprime(int x) {
        if (x <= 7) {
          if (x == 2 || x == 3 || x==5 || x == 7)
            return true;
        }
        int c = 7;
        if (x % 2 == 0)
          return false;
        if (x % 3 == 0)
          return false;
        if (x % 5 == 0)
          return false;
        int end = (int) Math.sqrt(x);
        while (c <= end) {
          if (x % c == 0) {
            return false;
          }
          c += 4;
          if (x % c == 0) {
            return false;
          }
          c += 2;
          if (x % c == 0) {
            return false;
          }
          c += 4;
          if (x % c == 0) {
            return false;
          }
          c += 2;
          if (x % c == 0) {
            return false;
          }
          c += 4;
          if (x % c == 0) {
            return false;
          }
          c += 6;
          if (x % c == 0) {
            return false;
          }
          c += 2;
          if (x % c == 0) {
            return false;
          }
          c += 6;
        }
        return true;
      }
      

  3.   

    panyoufei ~~~要学会分解问题。看3楼的代码:写一个计算质数的方法, 然后做一个int计数到6换行。这么2下就能解决问题,再反省下你自己的代码,一堆在那干了什么呢?等你想清楚这些“那我想把这些数输出到一个数组里,并计算数组的和     该怎么做?” 这个问题也不需要再问了
      

  4.   

    如果你的最终目的是求和,那把print语句后面增加一个 
    total+=i
    就可以了;