Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Main {
  public static void main(String[] args) {
    Sieve sieve = new Sieve(10_000);
    sieve.printAllPrimes();
  }
}

class Sieve {
  private final boolean[] sieve;

  Sieve(int max) {
    sieve = new boolean[max + 1];
    findAllPrimes();
  }
  
  private static final int SMALLEST_PRIME = 2;
  
  void printAllPrimes() {
    int count = 0;
    for (int i = SMALLEST_PRIME; i < sieve.length; i++) {
      if (sieve[i]) {
        System.out.printf("%d, ", i);
        count++;
      }
    }
    System.out.printf("%nFound %d primes up to %d%n", count, sieve.length-1);
  }  
  
  private void findAllPrimes() {
    initializeSieve();
    for (int i = SMALLEST_PRIME, limit = (int) Math.sqrt(sieve.length); i <= limit ; i++) {
      if (sieve[i]) {
        eliminateMultiples(i);
      }
    }
  }
  
  private void initializeSieve() {
    for (int i = SMALLEST_PRIME; i < sieve.length; i++) {
      sieve[i] = true;
    }
  }
  
  private void eliminateMultiples(int n) {
    for (int x = n + n; x < sieve.length; x += n) {
      sieve[x] = false;
    }
  }
}