Segmented Sieve (Print Primes in a Range)

Given a range [low, high], print all primes in this range?

For example, if the given range is [10, 20], then output is 11, 13, 17, 19.

class Main {
    public static ArrayList<Integer> countPrimes(int lowerLimit, int upperLimit) {
        int rootN = (int) Math.sqrt(upperLimit);
        // Find all the prime numbers upto rootN
        boolean[] primes = new boolean[rootN + 1];
        Arrays.fill(primes, true);
        for (int p = 2; p * p <= rootN; p++)
            if (primes[p])
                for (int j = p * p; j <= rootN; j += p)
                    primes[j] = false;
        ArrayList<Integer> primeNumbers = new ArrayList<>();
        for (int i = 2; i <= rootN; i++)
            if (primes[i])
                primeNumbers.add(i);
        // Now make a upperLimit-lowerLimit array
        // where arr[i] represents i+lowerLimit
        boolean[] arr = new boolean[upperLimit - lowerLimit + 1];
        Arrays.fill(arr, true);
        for (int x : primeNumbers) {
            int j = 0;
            while ((j + lowerLimit) % x != 0)
                j++;
            for (; j < arr.length; j += x)
                arr[j] = false;
        }
        ArrayList<Integer> ans = new ArrayList<>();
        // If the primes below rootN are within range aswell,
        // Then we need to add them aswell
        for (int x : primeNumbers)
            if (x >= lowerLimit)
                ans.add(x);
        for (int i = 0; i < arr.length; i++)
            if (arr[i] && i + lowerLimit != 1)
                ans.add(i + lowerLimit);
        return ans;
    }
}

Last updated