Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

return

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)?

like image 742
mythic Avatar asked Feb 11 '23 02:02

mythic


2 Answers

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.

like image 131
Mureinik Avatar answered Feb 12 '23 16:02

Mureinik


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++) {
like image 22
Asaph Avatar answered Feb 12 '23 15:02

Asaph