簡體   English   中英

該程序是否使用Eratosthenes篩網?

[英]Does this program use the Sieve of Eratosthenes?

我有一個作業,如下所示:使用Eratosthenes篩子來查找並打印從1到1000的所有素數。

請遵循與此類似的過程:

  1. 依次寫下所有要考慮的數字。
  2. 刪除1,因為它不被視為素數。
  3. 轉到下一個沒有划掉的數字; 保留它,但刪除該數字的所有倍數。
  4. 重復步驟3,直到您輸入的數字是所考慮的最大數字的一半。 在這一點上,所有未刪除的數字都是所需的質數。

您的算法可能與上述算法略有不同,但是速度很重要。

我使用我對數學和數組的知識編寫了該程序,但是在研究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" ); 
                    }

                }
            }
      } 
} 

你能幫忙的話,我會很高興!

問題在於,您在打印出結果之前沒有完成標記合成物的過程,這可能是因為您的循環是以一種混亂的方式嵌套的。

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);
    }
}

在此示例中,我已移動代碼以在執行篩分的循環外部打印質數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM