java 8 第14篇 给定数字,输出先前的所有的质素和非质素

本文介绍了一种使用Java实现的高效质数筛选算法。通过利用流(Stream)和lambda表达式,该算法能快速将指定范围内的自然数分为质数和非质数两组。文中详细解释了如何判断一个数是否为质数,以及如何优化这一过程。

/**
 * 测验:将数字按质数和非质数分区
 */
public class Demo02 {
    public static void main(String[] args) {
        Map<Boolean, List<Integer>> partitionPrimes = partitionPrimes(50);
        System.out.println("质素:" + partitionPrimes.get(true));
        System.out.println("非质素:" + partitionPrimes.get(false));
    }

    /**
     * 写一个方法,它接受参数int n,并将前n个自然数分为质数和非质数
     */
    public static Map<Boolean, List<Integer>> partitionPrimes(int n) {
        return IntStream.rangeClosed(2, n).boxed().collect(Collectors.partitioningBy(candidate -> isPrime2(candidate)));
    }

    /**
     * 判断一个数是否是质素
     *
     * @param candidate
     * @return
     */
    public static boolean isPrime(int candidate) {
        return IntStream.range(2, candidate).boxed().noneMatch(n -> candidate % n == 0);
    }
    /**
     * 判断一个数是否是质素:优化
     * @param candidate
     * @return
     */
    public static boolean isPrime2(int candidate) {
        int candidateRoot = (int) Math.sqrt((double) candidate);
        return IntStream.range(2, candidateRoot).boxed().noneMatch(n -> candidate % n == 0);
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值