Eratosthenes Sieve - Java java.lang

Java examples for java.lang:int prime

Description

Eratosthenes Sieve

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    static final int FIRST_PRIME = 2;

    public static ArrayList<Integer> EratosthenesSieve(int max)
            throws Exception {

        int currentRemove;
        int currentPrime = FIRST_PRIME;
        int size = max - 1;

        // Check input correctness
        if (size <= 0) {
            throw new Exception("Max number must greater than 2.");
        }//w  w  w  . jav a  2 s.com

        // Initialize candidates with true as default value
        ArrayList<Boolean> candidates = new ArrayList<Boolean>(
                Collections.nCopies(size, true));

        // Main loop
        while (true) {

            int i = currentPrime;
            // Remove all products of currentPrime
            while ((currentRemove = currentPrime * i++) <= max) {
                candidates.set(currentRemove - FIRST_PRIME, false);
            }

            // Find next prime
            int idx = currentPrime - FIRST_PRIME + 1;
            while (!candidates.get(idx)) {
                idx++;
            }
            currentPrime = idx + FIRST_PRIME;

            // Break if new prime square greater than max
            if (currentPrime * currentPrime > max) {
                break;
            }

        }

        // Collect all primes from candidates
        ArrayList<Integer> results = new ArrayList<Integer>();
        for (int i = 0; i < size; i++) {
            if (candidates.get(i)) {
                results.add(i + FIRST_PRIME);
            }
        }

        return results;
    }
}

Related Tutorials