java check if divisible

java check if divisible

To check if one number is divisible by another in Java, you can use the modulus operator (%) to calculate the remainder of the division. If the remainder is zero, then the first number is divisible by the second.

Here's an example of how to use the modulus operator to check if one number is divisible by another:

refer‮l:ot ‬autturi.com
int num1 = 10;
int num2 = 3;

if (num1 % num2 == 0) {
  // num1 is divisible by num2
} else {
  // num1 is not divisible by num2
}

In this example, the if statement will evaluate to true because 10 % 3 is equal to 0, indicating that num1 is divisible by num2.

You can also use this approach to check if a number is divisible by any other number. For example:

int num1 = 15;
int num2 = 5;

if (num1 % num2 == 0) {
  // num1 is divisible by num2
} else {
  // num1 is not divisible by num2
}

In this example, the if statement will again evaluate to true because 15 % 5 is equal to 0, indicating that num1 is divisible by num2.

Note that the modulus operator only works with integers, so if you need to check if a number with a decimal component is divisible by another number, you will need to use a different approach. One option is to use the Math.floorMod method, which calculates the remainder of the division in a way that is consistent with the behavior of the modulus operator for negative numbers.

Created Time:2017-11-03 00:14:48  Author:lautturi