Skip to content

Instantly share code, notes, and snippets.

@vasmarfas
Created March 10, 2025 01:39
Show Gist options
  • Save vasmarfas/cd1585168e214d239fad91a0ff906c66 to your computer and use it in GitHub Desktop.
Save vasmarfas/cd1585168e214d239fad91a0ff906c66 to your computer and use it in GitHub Desktop.
1.12.3.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class ParallelPrimeFinder {
@SuppressWarnings("unchecked")
public static List<Long> execute(int t, long l, long r) throws InterruptedException {
long rangeLength = r - l;
ExecutorService executor = Executors.newFixedThreadPool(t);
List<Future<List<Long>>> futures = new ArrayList<Future<List<Long>>>();
long chunkSize = rangeLength / t;
long currentNumber = l;
for (int i = 0; i < t; i++) {
long start = currentNumber;
long end = currentNumber + chunkSize;
currentNumber = end + 1;
if (i == t - 1) {
end = r;
}
long finalStart = start;
long finalEnd = end;
futures.add(executor.submit(() -> checkIfSimpleNumberAndAddToList(finalStart, finalEnd)));
}
executor.shutdown();
// Собираем результаты
List<Long> result = new ArrayList<Long>(List.of());
try {
for (Future<List<Long>> future : futures) {
result.addAll(future.get());
}
} catch (ExecutionException e) {
e.printStackTrace(); // Обработка ошибок выполнения
} finally {
executor.shutdown(); // Завершаем работу пула потоков
}
result.sort(null);
return result;
}
private static List<Long> checkIfSimpleNumberAndAddToList(long start, long end) {
List<Long> outList = new ArrayList<Long>(List.of());
for (long j = start; j <= end; j++) {
if (isPrime(j)) {
outList.add(j);
}
}
return outList;
}
private static boolean isPrime(long number) {
if (number == 1) {
return false;
}
boolean isPrime = true;
for (int i = 2; i < number; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment