P34 { public static List<Integer> primeNumbers_sieve(final int start, final int end) { boolean[] primes = new boolean[end + 1]; Arrays.fill(primes, true); for (int i = 2; i < primes.length; i++) { for (int j = i + 1; j < primes.length; j++) { primes[j] = !primes[j] || j % i == 0 ? false : true; } } List<Integer> primeNumbers = new ArrayList<>(); for (int i = start; i < primes.length; i++) { if (primes[i]) { primeNumbers.add(i); } } return primeNumbers; }  static List<Integer> primeNumbers(IntStream range); static List<Integer> primeNumbers_sieve(final int start, final int end);  }
@Test public void shouldGiveAllPrimeNumbersBetween2And10_sieve() throws Exception { List<Integer> primeNumbers = P34.primeNumbers_sieve(2, 10); assertThat(primeNumbers, hasSize(4)); assertThat(primeNumbers, hasItems(2, 3, 5, 7)); }
@Test public void shouldGiveAllPrimeNumbersBetween7And31_sieve() throws Exception { List<Integer> primeNumbers = P34.primeNumbers_sieve(7, 31); assertThat(primeNumbers, hasSize(8)); assertThat(primeNumbers, hasItems(7, 11, 13, 17, 19, 23, 29, 31)); }