使用java流判断一个数是否为素数

2 java primes java-stream

我正在阅读Cracking the Coding Interview,它有一个在 JShell 上运行的查找素数的示例

boolean isPrime(int n) {
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

然后我试图将其转换为java中的流,但发现这很困难,如上所述

boolean isPrimeStream(int n) {
  return IntStream.range(0, n) // how to do similar to for loop above
    .anyMatch(i -> n % i == 0);  // i think this is the reason for failure
}
Run Code Online (Sandbox Code Playgroud)

Nam*_*man 7

您应该将IntStream.noneMatch其用作:

boolean isPrimeStream(int n) {
    return IntStream.range(2, n) // note  division by zero possible in your attempt
                    .noneMatch(i -> n % i == 0);
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如 Andreas 的评论中指出的,使用range(2, n)避免被零除,因为除以 1 总是会导致条件为真并返回结果,否则返回结果false

返回此流中是否没有元素与提供的谓词匹配

您当前的代码正在使用IntStream.anyMatch

返回此流的任何元素是否与提供的谓词匹配

这就是为什么如果任何输入都满足指定的条件,它将返回,true而不是该方法应该返回false


如何执行与上面的 for 循环类似的操作

对于或更高版本,您可以使用IntStrem.iterateas

private boolean isPrimeStream(int n) {
    return IntStream.iterate(2, i -> i * i <= n, i -> i + 1) // similar to the loop
                    .noneMatch(i -> n % i == 0);
}
Run Code Online (Sandbox Code Playgroud)