How do I check if a Java integer is a multiple of another number? For example, if int j
is a multiple of 4.
To check if one number is a multiple of another number, use the modulo operator % . The operator returns the remainder when one number is divided by another number. The remainder will only be zero if the first number is a multiple of the second.
A multiple of a number should be able to divided by the initial number you are seeking the multiple for without any remainder. For example, 8 is a multiple of 2, and as 2 * 4 = 8, therefore 8/2 = 4. In this example, 2 and 4 are also factors of 8 and there are no remainders left. Compare this to dividing 12 by 5.
create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7. I create this function, when the number is between 0 to 99, by the next condition: if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7) return true; But what with number which is greater than 99?
If the sum of the digits of a number is divisible by 3, then the number is divisible by 3. Some examples of numbers divisible by 3 are as follows. The number 85203 is divisible by 3 because the sum of its digits (8 + 5 + 2 + 0 + 3 = 18) is divisible by 3.
Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:
if (j % 4 == 0) { // j is an exact multiple of 4 }
If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:
//j is a multiple of four if j % 4 == 0
The module operator performs division and gives you the remainder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With