Java Prime Number Hunter

New Articles

The PHP Java Extension

JSP File upload progress bar.

LPI Certification

The following code is an Implementation of the Sieve of Eratosthenes written using Java. It's purpose is to sieve the natural numbers and separate the primes from the composites. On this site you will find a PHP implementation as well as MySQL stored procedure that implements this algorithm. This code is much much faster than both those.

public class Eratosthenes
    int max;
    int primes[];
    public static void main(String args[])
        Eratosthenes erat = new Eratosthenes(10000000);
    public Eratosthenes(int max)
        this.max = max;
    public void find_primes()
        int i,j,k, divisor, offset;
        double sqrt = Math.sqrt(max)+1;
        int tmp[];
        if(max  > 100)
            primes = new int[max/2];
            primes = new int[max];
        primes[0] = 2;
        primes[1] = 3;
        for(i=2,j=5; j 

For completeness sake you can dump the numbers to a file. But this code is so fast, that reading from disk would be slower for small numbers.

        File f = new File("/dev/shm/primes.txt");
        FileWriter writer = new FileWriter(f);
    } catch (IOException ex)

Like the PHP version, this code also happens to be a memory hog. if you want find primes larger than about 10,000,000 you will need to change the amount of memory allocated to the JVM. If that is not an option, you can change the first for loop (the one that populates the array) so that numbers divisable by 5,7 and 11 are also left out. That would reduce the memory consumption by a little bit.