简体   繁体   中英

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. The only other obvious reason is that the second method only uses a single return statement.

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. This makes a lot of sense in languages where you have to free resources explicitly, but doesn't have any functional impact in 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.

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 .

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:

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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