forked from MaXal/PerformanceInvestigation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PrimeCalculator.java
82 lines (69 loc) · 2.74 KB
/
PrimeCalculator.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Moved to package to simplify execution
package com.koltsa;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class BigIntegerIterator {
private final List<String> contain = new ArrayList<>(500);
private final List<Integer> reference = new ArrayList<>(500);
BigIntegerIterator(int i) {
contain.add("" + i + "");
reference.add(i);
}
Integer getContain() {
return Math.max(Integer.decode(contain.get(0)), reference.get(0));
}
}
public class PrimeCalculator {
public static void main(String[] args) {
System.out.println(PrimeCalculatorSieveOfEratosthenes.getPrimes(Integer.parseInt(args[0])));
}
public static List<Integer> getPrimes(int maxPrime) throws InterruptedException {
List<Integer> primeNumbers = Collections.synchronizedList(new LinkedList<>());
List<BigIntegerIterator> myFiller = Stream.generate(new Supplier<BigIntegerIterator>() {
int i = 2;
@Override
public BigIntegerIterator get() {
return new BigIntegerIterator(i++);
}
}).limit(maxPrime).collect(Collectors.toList());
for (BigIntegerIterator integer : myFiller) {
primeNumbers.add(integer.getContain());
}
List<Integer> primeNumbersToRemove = Collections.synchronizedList(new LinkedList<>());
CountDownLatch latch = new CountDownLatch(maxPrime);
ExecutorService executors = Executors.newFixedThreadPool(Math.max(maxPrime / 100, 3000));
synchronized (primeNumbersToRemove) {
for (Integer candidate : primeNumbers) {
executors.submit(() -> {
try {
isPrime(primeNumbers, candidate);
} catch (Exception e) {
primeNumbersToRemove.add(candidate);
}
latch.countDown();
});
}
}
latch.await();
executors.shutdownNow();
for (Integer toRemove : primeNumbersToRemove) {
primeNumbers.remove(toRemove);
}
return primeNumbers;
}
private static void isPrime(List<Integer> primeNumbers, Integer candidate) throws Exception {
for (Integer j : primeNumbers.subList(0, candidate - 2)) {
if (candidate % j == 0) {
throw new Exception();
}
}
}
}