In the spirit of premature optimisation, here's a fast method based on modular aritmeticarithmetic:
import java.math.BigInteger;
private static final int MULTIPLIER =
BigInteger.valueOf(3).modInverse(BigInteger.valueOf(2).pow(32)).intValue();
private static final int LOWER_LIMIT = Integer.MIN_VALUE / 3;
private static final int UPPER_LIMIT = Integer.MAX_VALUE / 3;
public static boolean divideFast(int i) {
int j = i * MULTIPLIER;
return LOWER_LIMIT <= j && j <= UPPER_LIMIT;
}
The idea is that in Java, multiplication is modulo 2^32232 (since it wraps on overflow), and in modular arithmetic you can divide by multiplying - which is generally faster than dividing. Every odd number has a "reciprocal" - a number that you can multiply it by to give 1 - since odd numbers are coprime to 2^32232. The reciprocal of 3 is MULTIPLIER.
If i is divisible by 3 in regular integer arithmetic, then i * MULTIPLIER will be i / 3. If i is not divisible by 3, then it's still true that 3 * (i * MULTIPLIER) === i modulo 2^32232, but only because multiplication wraps on overflow.
So, the numbers that are divisible by 3 are precisely the numbers where we can multiply i * MULTIPLIER by 3 without overflow. I.e, the numbers where i * MULTIPLIER is between Integer.MIN_VALUE / 3 and INTEGER.MAX_VALUE / 3.
In my benchmark, this method works out at 0.72ns per check, versus 0.93ns per op for the next closest, Maartinus@maaartinus.