by Lars Vogel

Follow me on twitter

Lars Vogel on Google+

Determine Prime Number with the Sieve of Eratosthenes - Algorithm in Java

Lars Vogel

Version 0.1

17.05.2009

Revision History
Revision 0.1 17.05.2009 Lars
Vogel
Created

Abstract

This article describes the calculation of prime numbers with the sieve of Eratosthenes in Java


Table of Contents

1. Prime Factorization
2. Implementation in Java
3. Thank you
4. Questions and Discussion
5. Links and Literature
5.1. Source Code
5.2. General

1. Prime Factorization

A prime is an integer greater then one whole only positive divisors are one and itself.

The prime counting function for a number N (also known as pie(N)) is the number of primes less or equal to N.

The following algorithm determines all prime numbers until a certain value.

2. Implementation in Java

Create a Java project "de.vogella.algorithms.primenumbers".

Create the following program.

			
package de.vogella.algorithms.primenumbers;

import java.util.ArrayList;
import java.util.List;

// Using the sieve of Eratosthenes
public class PrimeNumbers {
	public static List<Integer> calcPrimeNumbers(int n) {
		boolean[] isPrimeNumber = new boolean[n + 1]; // boolean defaults to
		// false
		List<Integer> primes = new ArrayList<Integer>();
		for (int i = 2; i < n; i++) {
			isPrimeNumber[i] = true;
		}
		for (int i = 2; i < n; i++) {
			if (isPrimeNumber[i]) {
				primes.add(i);
				// Now mark the multiple of i as non-prime number
				for (int j = i; j * i <= n; j++) {
					isPrimeNumber[i * j] = false;
				}
			}

		}

		return primes;
	}

	public static void main(String[] args) {
		List<Integer> calcPrimeNumbers = calcPrimeNumbers(21);
		for (Integer integer : calcPrimeNumbers) {
			System.out.println(integer);
		}
		System.out.println("Prime counting function (Pie(N)) : "
				+ calcPrimeNumbers.size());
	}
}

		

3. Thank you

Please help me to support this article:

Flattr this

4. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.de Google Group. I have created a short list how to create good questions which might also help you.

5. Links and Literature

5.1. Source Code

http://www.vogella.de/code/codejava.html Source Code of Examples

5.2. General

Not listed yet