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));
}
测试用例
本文介绍了一种高效的素数判断算法,通过计算n的平方根并取整,减少不必要的运算,实现快速判断。此外,还提供了一个算法,用于将指定范围内的整数按是否为素数进行分区。
1793

被折叠的 条评论
为什么被折叠?



