且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用java流来查找数字是否为素数

更新时间:2022-02-03 07:32:52

问题一,你应该使用 noneMatch (不是 anyMatch )。问题二,你的范围是关闭的。使用 rangeClosed (或添加一个),这应该是 n 的平方根(不仅仅是 n ) - 您在第一次测试中以2作为初始值开始。此外,您还可以使方法 static 。比如,

Problem one, you should be using noneMatch (not anyMatch). Problem two, your range is off. Use rangeClosed (or add one to your end) which should be the square root of n (not just n) - and you started with 2 as an initial value in your first test. Also, you might as well make the method static. Like,

static boolean isPrimeStream(int n) {
    return IntStream.rangeClosed(2, (int) Math.sqrt(n)) 
            .noneMatch(i -> n % i == 0);
}

此外,我们可以通过处理改进您的第一个示例2 作为特例。这允许你从三个开始,并以两个递增的方式跳过所有偶数值。

Also, we can improve your first example by handling 2 as a special case. That allows you to begin with three and increment by two skipping all even values.

static boolean isPrime(int n) {
    if (n == 2) {
        return true;
    } else if (n % 2 == 0) {
        return false;
    }
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}