Home > Software design >  Division and Modulus in Java
Division and Modulus in Java

Time:12-16

Create a method names dividesEvenly(a,b) that can receive two integers, a and b, return true if a can be divided evenly by b. Return false otherwise.example : dividesEvenly(8, 4) ➞ true # 8/4 = 2 dividesEvenly(10, 2) ➞ false # 10/2 = 5

CodePudding user response:

I think you are looking for the modulo % opperator. To check whether a number, in your case a/b, is even you can do this: (a/b)%2 == 0

The complete methode would lock something like this:

public boolean dividesEvenly(int a, int b) {
    return (a/b)%2==0;
}

CodePudding user response:

This question is about the modulus operator, in java a % symbol, also known as the remainder operator.

See also the documentation

If "a" can be divided evenly by "b", the result of a / b will be an even number. You can then check this with a modulus operation.

Writing this as a method in java, you have

public boolean dividesEvenly(int a, int b) {
    int division = a / b;
    return division % 2 == 0;
}

These two steps are summarized as follows:

  1. Divide a by b and assign this value to a variable (called "division" in the code)
  2. Check that if this division were divided by two it would have no remainder (division mod 2 equals zero). If this is the case, then it divides evenly. Otherwise (division mod 2 not zero) the result of the division is an odd number.
  •  Tags:  
  • java
  • Related