这个程序是否使用了Eratosthenes的Sieve?

时间:2015-02-27 21:50:05

标签: java arrays

我的作业如下, :使用Eratosthenes的筛子找到并打印出从1到1000的所有素数。

按照与此类似的程序:

  1. 按顺序记下所有要考虑的号码。
  2. 交叉1,因为它不被视为素数。
  3. 转到下一个未划掉的号码;离开它,但划掉那个数字的所有倍数。
  4. 重复步骤3,直到您输入的数字是所考虑的最大数字的一半。此时,所有未被划掉的数字都是期望的素数。
  5. 您的算法可能与上述算法略有不同,但速度很重要。

    我使用数学和数组的知识编写了这个程序但是当我在研究Sieve时,我不知道这是否是方法。

    public class PrimeSieve
     {
    
         public static void main( String[] args) 
         { 
             int max=1000;
             calcPrimes( max ); 
            } 
    
            public static void calcPrimes( int max ) 
            { 
                // each boolean value indicates whether corresponding index 
                // position is composite (non-prime) 
                boolean[] array = new boolean[max +1 ]; 
    
                // mark composites as true 
                 for (int i = 2; i <= (int) Math.sqrt( max ); i++) 
                 {
                     for (int j = i*i; j <= max; j += i) array [j ] = true; 
                     {
    
                 // print indexes with corresponding false values 
                        for (int k = 2;k <= max; k++) 
                        {
    
                            if ( !array[ k ] ) 
                            System.out.format( k + "\n" ); 
                        }
    
                    }
                }
          } 
    } 
    

    任何帮助都会很好!

1 个答案:

答案 0 :(得分:3)

问题是你在打印结果之前没有完成标记复合的过程,可能是因为你的循环以一种混乱的方式嵌套。

public static void calcPrimes(int max) {
    // each boolean value indicates whether corresponding index
    // position is composite (non-prime)
    boolean[] array = new boolean[max + 1];

    // mark composites as true
    for (int i = 2; i <= (int) Math.sqrt(max); i++) {
        for (int j = i*i; j <= max; j += i) array[j] = true;
    }

    // print indexes with corresponding false values
    for (int k = 2; k <= max; k++) {
        if (!array[k]) System.out.println(k);
    }
}

在这个例子中,我已经移动代码来打印执行筛子的循环之外的素数。