Search code examples
javadebuggingcompiler-errorsboolean-operations

Implementing a prime sieve in Java using booleans


I am trying to implement a prime sieve in Java so that I can figure out the sum of all prime numbers less than a certain maximum. I tried to do it using a method PrimeSieve and using an array of booleans which I make true if the number is composite by taking a prime and considering all integer multiples less than the max.

But I keep getting compiler errors when trying to run the program and I can't figure out what's wrong:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error, insert ". class" to complete Expression The type of the expression must be an array type but it resolved to Class Syntax error on token "i", delete this token Syntax error, insert ". class" to complete Expression The type of the expression must be an array type but it resolved to Class
at Problem3.PrimeSieve(Problem3.java:11)
at Problem3.main(Problem3.java:26)

public class Problem3 {

    public static boolean[] PrimeSieve(int max) {

        // automatically all entries are false
        boolean[] isPrime = new boolean[max];

        // when a number isn't prime make the entry true

        for (int i = 0; i < max; i++) {
            if (!boolean[i]) {
                for (int j = 2i; j < max; j += i) {
                    boolean[j] = true;
                }
            } else {}
        }

        // return the isPrime boolean with all the primes as false
        return isPrime;
    }

    public static void main(String[] args) {

        boolean[] Primes = new boolean[100];
        Primes = PrimeSieve(100);

        int i = 0;
        int ans = 0;

        while (i < 100) {
            if (!Primes[i]) {
                ans += i;
                i++;
            } else { 
                i++; 
            }
        }

        System.out.println(ans);
    }
}

Any help in resolving these errors would be greatly appreciated


Solution

  • You got 2 problems:
    1) You using the name of the type instead the name of the array.
    So boolean[i] should be changed into isPrime[i].
    2) Java don't understand 2i as "two times i". You need to write that 2*i.

    This will make your code compile:

     for (int i = 0; i < max; i++) {
                        if (!isPrime[i]) {
                            for (int j = 2*i; j < max; j += i) {
                                isPrime[j] = true;
                            }
                        } else {}  // By the way - This is really not necessary
                    }