public static boolean isPrime2(int n){
int squareRoot = (int)Math.sqrt((double)n);
return IntStream.rangeClosed(2, squareRoot).noneMatch(i -> n%i==0);
}
如果不能被[2, n)这个范围的数整除,n就是素数。把n换成n的平方根并且取整,是个简便算法,可以减少运算量。
public static Map<Boolean, List<Integer>> partitionPrime(int n){
return IntStream.rangeClosed(2, n).boxed()
.collect(Collectors.partitioningBy(candidate -> isPrime2(candidate)));
}
算出[2, n]这个范围那些是素数。
public static void main(String[] args) {
System.out.println(partitionPrime(100));
}
测试用例