Question
How can I determine if a given integer in Java is a multiple of another integer?
int n = 15; // number to check
int divisor = 5; // divisor
boolean isMultiple = n % divisor == 0; // check if multiple
System.out.println(n + " is a multiple of " + divisor + ": " + isMultiple);
Answer
In Java, determining whether an integer is a multiple of another integer can be efficiently achieved using the modulus operator (%). This operator returns the remainder of a division operation. If the result is zero when the first number is divided by the second, it indicates that the first number is a multiple of the second.
public class CheckMultiple {
public static void main(String[] args) {
int number = 20; // number to check
int divisor = 4; // divisor
boolean isMultiple = checkMultiple(number, divisor);
System.out.println(number + " is a multiple of " + divisor + ": " + isMultiple);
}
public static boolean checkMultiple(int num, int div) {
// Avoid division by zero
if (div == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return num % div == 0;
}
}
Causes
- Incorrect use of the modulus operator.
- Mistaking the order of operands.
- Using primitive data types without checking for overflows.
Solutions
- Utilize the modulus operator correctly to check for remainders appropriately.
- Ensure the divisor is not zero to prevent arithmetic exceptions.
- Implement input validation to handle edge cases like negative numbers or zero.
Common Mistakes
Mistake: Forgetting to handle division by zero.
Solution: Always check if the divisor is zero before performing modulus operations.
Mistake: Misusing the modulus operator resulting in incorrect results.
Solution: Confirm that the operator is used as intended; check for remainders.
Helpers
- Java check integer multiple
- Java modulus operator
- check if number is multiple Java