簡體   English   中英

Eratosthenes素數程序篩

[英]Sieve of Eratosthenes Prime Number Program

在我的實驗室中,我被要求編寫一個程序,使用Eratosthenes篩子將100以下的質數打印出來。 但是,我已經編寫了程序,並且正在打印出許多非素數,例如27,33和99。 不好意思的解釋很抱歉,但這是我的代碼,我希望有人能提供一些建議或解決方案。 謝謝!

public class SOE {
    public static void main(String args[]) {
        boolean [] myArray = new boolean[100];
        int j=0;

        for(int i=0;i<myArray.length;i++) { //Initialises array
            myArray[i] = false;
        }

        for(int i=2;i<myArray.length;i++) { //loops through slot numbers
            while(j<myArray.length) { //loops through multiples
                if(j%i == 0 || j%5==0) {
                    myArray[j] = true;
                }
                j++;
            }
        }

        for(int i=0;i<myArray.length;i++) { //prints out prime numbers
            if(myArray[i]==false) {
                System.out.println(i);
            }
        }
    }
}

Eratosthenes篩網通常簡單得多:

for(int i = 2; i < myArray.length; i++) {
    if (myArray[i]) {continue;}
    j = 2 * i;
    while(j < myArray.length) {
        myArray[j] = true;
        j += i;
    }
}

這將為了消除4, 6, 8, ... ,然后6, 9, ... ,則跳過4 ,然后10,... ,則跳過6 ...等

暫無
暫無

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

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