Skip to content

Instantly share code, notes, and snippets.

@mcmullm2-dcu
Last active February 4, 2018 10:01
Show Gist options
  • Save mcmullm2-dcu/b53f2f6a6988d45fb032b58fa5c815f1 to your computer and use it in GitHub Desktop.
Save mcmullm2-dcu/b53f2f6a6988d45fb032b58fa5c815f1 to your computer and use it in GitHub Desktop.
Java implementation of the Sieve of Eratosthenes, an algorithm to calculate prime numbers.
/**
* Implementation of the sieve of Eratosthenes for finding all the primes up to
* a given number (MAX in this case).
* From the command line:
* Step 1 (compile): javac PrimesSieve.java
* Step 2 (run): java PrimesSieve
*/
public class PrimesSieve {
public static void main(String[] args) {
final int MAX = 1_000_000;
// Create an array of boolean values indicating whether a number is prime.
// Start by assuming all numbers are prime by setting them to true.
boolean[] primes = new boolean[MAX];
for (int i=0; i<primes.length; i++) {
primes[i] = true;
}
// Loop through a portion of the array (up to the square root of MAX). If
// it's a prime, ensure all multiples of it are set to false, as they
// clearly cannot be prime.
for (int i=2; i<Math.sqrt(MAX)+1; i++) {
if (primes[i-1]) {
for (int j=(int) Math.pow(i,2); j<=MAX; j+=i) {
primes[j - 1] = false;
}
}
}
// Output the results
int count = 0;
for (int i = 2; i < MAX; i++) {
if (primes[i - 1]) {
System.out.println(i);
count++;
}
}
System.out.printf("There were %d primes up to %d", count, MAX);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment