简体   繁体   English

检查数字是否为素数的这两种方法有什么区别?

[英]What is the difference between these two methods for checking if a number is a prime?

I wrote a method for checking if a number is a prime: 我写了一个检查数字是否为素数的方法:

static boolean isPrime(int x) {
        for (int i = 2; i <= Math.sqrt(x); i++) {
            if (x % i == 0)
                return false;    
        }
        return true;
    }

In a collection of exercises we're learning from, the solution is: 在我们正在学习的一系列练习中,解决方案是:

static boolean isPrime(int x) {
    boolean hasDivisors = false;
    for (int i = 2; i <= Math.sqrt(x); i++) {
      if (x % i == 0) {
        hasDivisors = true;
        break;
      }
    }
    return !hasDivisors;
}

In my case, If i find a divisor, I return that the number is not a prime ( return false ) and that replaces the need for a break in second method. 在我的情况下,如果我找到一个除数,我返回该数字不是素数( return false )并且替换了第二种方法break的需要。 The only other obvious reason is that the second method only uses a single return statement. 唯一明显的原因是第二种方法只使用一个return语句。

Is there a reason for this (speed/memory wise)? 有这个原因(速度/记忆明智)?

It's a matter of style, mostly. 这主要是风格问题。 Some coding conventions dictate that a method have only a single return statement. 某些编码约定规定方法只有一个return语句。 This makes a lot of sense in languages where you have to free resources explicitly, but doesn't have any functional impact in Java. 这在您必须明确释放资源的语言中很有意义,但在Java中没有任何功能影响。

Personally, I prefer to just return as soon as you know the result (like in the first snippet), but again, it's a matter of personal style. 就个人而言,我更愿意在你知道结果后立即return (就像在第一个片段中一样),但同样,这是个人风格的问题。

Both solutions work and both are valid for all the reasons you have already identified. 这两种解决方案都有效,并且两者都适用于您已经确定的所有原因。 Good analysis. 好的分析。 As others have noted, the differences are purely stylistic. 正如其他人所指出的,差异纯粹是风格上的。 Here is an interesting discussion about the single return statement style in java . 以下是关于java中单个return语句样式有趣讨论

Performance-wise, I wouldn't expect a significant difference between the 2 approaches. 在性能方面,我不希望两种方法之间存在显着差异。 But if you want to be certain, perform a benchmark test. 但如果您想确定,请执行基准测试。 If you want a real performance boost, you can eliminate the expensive call to Math.sqrt() by replacing: 如果您希望获得真正的性能提升,可以通过替换以下内容来消除对Math.sqrt()的昂贵调用:

for (int i = 2; i <= Math.sqrt(x); i++) {

with

for (int i = 2; i*i <= x; i++) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM