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++) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With