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

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

本文介绍了使用java流来查找数字是否为素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

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

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

then I am trying to convert this to streams in java, but finding this difficult as mentioned

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
}


推荐答案

问题一,你应该使用 noneMatch (不是 anyMatch )。问题二,你的范围是关闭的。使用 rangeClosed (或添加一个),这应该是 n 的平方根(不仅仅是<$ c) $ c> 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;
}

这篇关于使用java流来查找数字是否为素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:44