Sean
Sean

Reputation: 1

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

Upvotes: 0

Views: 652

Answers (1)

njzk2
njzk2

Reputation: 39386

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

Upvotes: 1

Related Questions