For two arbitrary numbers, the best way to check is to check whether a % b == 0
. The modulus operator has different performance based on the hardware, but your compiler can figure this out much better than you can. The modulus operator is universal, and your compiler will figure out the best sequence of instructions to emit for whatever hardware you're running on.
If one of the numbers is a constant, your compiler might optimize by doing some combination of bit shifts and subtractions (mostly for powers of two), since hardware div/mod is slower than addition or subtraction, but on modern processors the latency (already only a few nanoseconds) is hidden by tons of other performance tricks, so you needn't worry about it. No hardware computes modulus by repeated division (some old processors did division by repeated bit shifts and subtraction, but they still used specialized hardware for this, so it's still faster to have the hardware do it than to try to emulate it in software). Most modern ISAs actually compute both division and remainder in one instruction.
The only optimization that might be useful is if the divisor is a power of two. Then you can use &
to mask the low-order bits (by divisor - 1) and check the result against zero. For example, to check if a
is divisible by 8, a & 7 == 0
is equivalent. A good compiler will do this for you, so stick with just stick with %
.