Skip to content

Instantly share code, notes, and snippets.

@fmcarvalho
Created May 16, 2016 21:47
Show Gist options
  • Save fmcarvalho/b570f42de5f68e293758e258b92bf9b2 to your computer and use it in GitHub Desktop.
Save fmcarvalho/b570f42de5f68e293758e258b92bf9b2 to your computer and use it in GitHub Desktop.
Implementation of two approaches to calculate N prime numbers using Java 8 Streams (based on Chapter 6 proposal of Java 8 in Action)
package primes;
import org.openjdk.jmh.annotations.Benchmark;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.stream.IntStream;
/**
* Based on Chapter 6 of Java 8 in Action
* @author Miguel Gamboa
* created on 16-05-2016
*/
public class Primes {
/*==================================================
==================================================*/
private static boolean isPrime(int n) {
int root = (int) Math.sqrt(n);
return IntStream
.rangeClosed(2, root)
.noneMatch(div -> n%div == 0);
}
private static List<Integer> primes(int max) {
return IntStream
.range(2, max)
.filter(Primes::isPrime)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
}
/*==================================================
==================================================*/
private static boolean isPrimeOpt(List<Integer> primes, int n) {
int root = (int) Math.sqrt(n);
return takeWhile(primes, root)
.stream()
.noneMatch(div -> n%div == 0);
}
private static List<Integer> takeWhile(List<Integer> src, int max) {
int i;
for(i = 0; i < src.size() && src.get(i) <= max; i++) {}
return src.subList(0, i);
}
private static List<Integer> primesOpt(int max) {
ArrayList<Integer> res = new ArrayList<>();
return IntStream
.range(2, max)
.filter(n -> Primes.isPrimeOpt(res, n))
.collect(() -> res, ArrayList::add, (l1, l2) -> {});
}
@Benchmark
public int testPrimes() {
return primes(10_000).size();
}
@Benchmark
public int testPrimesOpt() {
return primesOpt(10_000).size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment