forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSieve.java
More file actions
37 lines (30 loc) · 1.01 KB
/
Sieve.java
File metadata and controls
37 lines (30 loc) · 1.01 KB
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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Sieve {
private int maximalPrime;
private List<Integer> primes;
public Sieve(int maximalPrime) {
this.maximalPrime = maximalPrime;
this.primes = calculatePrimes();
}
public List<Integer> getPrimes() {
return primes;
}
private List<Integer> calculatePrimes() {
List<Integer> primes = new ArrayList<>();
LinkedList<Integer> candidates = IntStream.range(2, maximalPrime + 1)
.boxed()
.collect(Collectors.toCollection(LinkedList::new));
while (candidates.size() > 0) {
Integer prime = candidates.remove();
primes.add(prime);
candidates = candidates.stream()
.filter(x -> x % prime != 0)
.collect(Collectors.toCollection(LinkedList::new));
}
return primes;
}
}