Skip to content

Instantly share code, notes, and snippets.

@kasecato
Last active April 8, 2016 02:00
Show Gist options
  • Save kasecato/941a7ceb8e106c52c0971303487a45b2 to your computer and use it in GitHub Desktop.
Save kasecato/941a7ceb8e106c52c0971303487a45b2 to your computer and use it in GitHub Desktop.
ParallelTest Java
import java.util.stream.IntStream;
public class ParallelTest {
public static void main(String[] args) {
final int max = 10000000;
long startTime = System.currentTimeMillis();
ParallelTest pt = new ParallelTest();
long primes = pt.countPrimes(max);
System.out.println(primes);
long stopTime = System.currentTimeMillis();
System.out.println(stopTime - startTime);
}
private long countPrimes(final int max) {
return IntStream
.range(1, max)
.parallel()
.filter(this::isPrime)
.count();
}
private boolean isPrime(final long n) {
if (n < 2) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i + 1) == 0) return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment