Skip to content

Instantly share code, notes, and snippets.

@marcgeld
Created May 27, 2020 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcgeld/bcb4c696dd3b61e1e6c03b855c3bedbf to your computer and use it in GitHub Desktop.
Save marcgeld/bcb4c696dd3b61e1e6c03b855c3bedbf to your computer and use it in GitHub Desktop.
Generates a list of as many primes as possible within 100 milliseconds OR when there is a common divisor >1 for the newly generated prime and last prime on list
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class SlowCalc {
public static void main(String[] args) {
List<BigInteger> primeList = Collections.synchronizedList(new ArrayList<BigInteger>());
ExecutorService executorService = Executors
.newSingleThreadExecutor();
Future<BigInteger> future = (Future<BigInteger>) executorService
.submit(() -> {
BigInteger gcd = null;
// SMALL_PRIME_THRESHOLD - The cutoff of 95 was chosen empirically for best performance.
// Here we awoid best performance, this will be handled as a large prime
// We also add a high certainty to get a long running calculation
BigInteger val = new BigInteger(200, 10000, new Random());
primeList.add(val);
do {
val = new BigInteger(200, 10000, new Random());
// Calculate the greatest common divisor
gcd = primeList.get(primeList.size() - 1).gcd(val);
primeList.add(val);
// As long as the compared numbers are primes and greatest common divisor
// is one this will continue forever…
} while (!Thread.currentThread().isInterrupted() && BigInteger.ONE.equals(gcd));
return gcd;
});
try {
BigInteger result = future.get(100, TimeUnit.MILLISECONDS);
System.out
.println(String.format("a greatest common divisor >1 was found: %s", result.toString()));
} catch (InterruptedException | ExecutionException | TimeoutException e) {
future.cancel(true);
}
executorService.shutdownNow();
while (true != executorService.isTerminated()) {
try {
executorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
}
System.out.println(String.format("A list of primes with %d elements", primeList.size()));
for (int i = 0; i < primeList.size(); i++) {
System.out.println(String.format("Value #%d: %s", i, primeList.get(i).toString()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment