Improving isPrime method 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 &lt; 1) {
        throw new IllegalArgumentException(
            "Argument must be a positive integer." +
            "\n Argument was: " + num + "."
        );
    }
    if (num &lt;= 3){ return num &gt; 1; }
    if ((num &amp; 1) == 0) { return false; }

    for (int i = 5; i * i &lt;= 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?
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 &amp; 1) == 0 is perfectly clear, however the previous statement, if (num &lt;= 3) return num &gt; 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 &lt;= 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.