All puzzles
Per page
A
Frequency · Divisibility · Range

Count the multiples

Count how many numbers from start to end, including both, divide evenly by d.

countMultiples(10, 20, 5) returns 3.

10 strips: A1 to A10

if (i % d == 0) {
A1
public static int countMultiples(int start, int end, int d) {
A2
}
A3
for (int i = start; i <= end; i++) {
A4
}
A5
int count = 0;
A6
return count;
A7
count++;
A8
for (int i = start; i < end; i++) {
A9
}
A10

Answer key: A. Count the multiples

Order: A2, A6, A4, A1, A8, A5, A10, A7, A3. Extra: A9

public static int countMultiples(int start, int end, int d) {
	int count = 0;
	for (int i = start; i <= end; i++) {
		if (i % d == 0) {
			count++;
		}
	}
	return count;
}

Extra strip: for (int i = start; i < end; i++) {. i < end stops before end, so 20 is never checked and the method returns 2.