Divisibility

Basic Algorithms
≈ 2 min read

The remainder tells you about divisibility

A number a is divisible by b with no remainder when a % b == 0. This simple test is the basis of many problems: finding multiples, counting divisors, determining parity, or checking common numeric properties.

int number = 42;

if (number % 7 == 0) {
    System.out.println("Divisible");
}

Here 42 % 7 is zero, so the number is divisible by seven.

Finding divisors

A divisor of a number is a value that divides the number with no remainder. The most direct way to find the divisors of a positive number is to enumerate candidates and test each one with %.

int number = 12;

for (int divisor = 1; divisor <= number; divisor++) {
    if (number % divisor == 0) {
        System.out.println(divisor);
    }
}

For 12, this finds 1, 2, 3, 4, 6, and 12. For now, the important part is the connection between enumeration and the divisibility test; ways to reduce the number of checks will appear later.

Several divisibility conditions

The checks can be combined with ordinary logical operators. For example, a number is divisible by both 3 and 5 if both remainders are zero.

boolean divisibleByBoth = number % 3 == 0 && number % 5 == 0;

It is important to read such a condition literally: each part represents a separate requirement, and && means that both must be true.

You cannot divide by zero. The operation number % 0, just like integer division by zero, causes an ArithmeticException.