简体   繁体   English

Eratosthenes素数程序筛

[英]Sieve of Eratosthenes Prime Number Program

For my lab I have been asked to write a program which prints off the prime numbers under 100 using the Sieve of Eratosthenes. 在我的实验室中,我被要求编写一个程序,使用Eratosthenes筛子将100以下的质数打印出来。 However I have written the program and a number of non-prime numbers such as 27,33 and 99 are being printed out. 但是,我已经编写了程序,并且正在打印出许多非素数,例如27,33和99。 Sorry for the poor explanation but here is my code, i hope someone can offer some advice or a solution. 不好意思的解释很抱歉,但这是我的代码,我希望有人能提供一些建议或解决方案。 Thanks! 谢谢!

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 sieve is usually much simpler : 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;
    }
}

That will eliminate in order 4, 6, 8, ... , then 6, 9, ... , then skip 4 , then 10,... , then skip 6 ... and so on 这将为了消除4, 6, 8, ... ,然后6, 9, ... ,则跳过4 ,然后10,... ,则跳过6 ...等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM