HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Improving isPrime method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
isprimeimprovingmethod

Problem

I've been doing some programming challenges and problems lately and it seems like many involve primes. I concluded that I would benefit from optimizing how I'm checking for them. Currently I'm using the following method:

private static boolean isPrime(int num) {
    if (num  1; }
    if ((num & 1) == 0) { return false; }

    for (int i = 5; i * i <= num; i += 2) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}


Sometimes altering longs.

Excluding bitwise hacks that would likely come at the cost of readability is this as good as it gets or is there some enhancement that would raise performance?

Solution

When misused, private access can frequently result in reduced opportinutues for code reuse, such as in this case. Self-contained static methods in particular should almost never be private, but rather should be moved into a separate utilities class and marked public.

At the same time, you should add javadoc to the method, to further facilitate code reuse:

/**
 * Tests whether a number is prime or not.
 * @param num The number to test.
 * @returns {@code true} if {@code num} is prime, {@code false} otherwise.
 * @throws IllegalArgumentException if {@code num} is zero or negative.
 */


As for readability, I think that (num & 1) == 0 is perfectly clear, however the previous statement, if (num 1;, is a little bit unclear. You should replace it with a simple check for one, if (num == 1) return false; and another if (num <= 3) return true; after it.

Note that if you start the loop at 5, you missclassify 9, 15, and 21, which you can see in this ideone sketch: https://ideone.com/Jnn6QU. They are missed because they are less than 25 but not divisible by two. You should start the loop at 3 in order to catch those numbers.

You may wish to consider using BigInteger.isProbablePrime instead of this method, however, as it is much faster for large values. While a true return from that method does not guarantee that the number is prime, you can tune its certainty to your needs.

Code Snippets

/**
 * Tests whether a number is prime or not.
 * @param num The number to test.
 * @returns {@code true} if {@code num} is prime, {@code false} otherwise.
 * @throws IllegalArgumentException if {@code num} is zero or negative.
 */

Context

StackExchange Code Review Q#77178, answer score: 8

Revisions (0)

No revisions yet.