简体   繁体   中英

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. However I have written the program and a number of non-prime numbers such as 27,33 and 99 are being printed out. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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