Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Check if integer is multiple of a number

Tags:

java

How do I check if a Java integer is a multiple of another number? For example, if int j is a multiple of 4.

like image 738
Shaun Avatar asked Nov 05 '11 22:11

Shaun


People also ask

How do you check if a number is a multiple of a number Java?

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.

How do you check if a number is multiple of a number?

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.

How do you check if a number is a multiple of 7 in Java?

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?

How do you find if a number is a multiple of 3 Java?

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.


2 Answers

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 } 
like image 165
Mark Byers Avatar answered Oct 01 '22 22:10

Mark Byers


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.

like image 35
V9801 Avatar answered Oct 01 '22 22:10

V9801