What's the Syntax for Mod in Java

What's the syntax for mod in java

Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %. For your exact example:

if ((a % 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}

This can be simplified to a one-liner:

isEven = (a % 2) == 0;

Understanding The Modulus Operator %

(This explanation is only for positive numbers since it depends on the language otherwise)

Definition

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

Euclidean Division

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

Calculation

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b
  • floor(a / b) represents the number of times you can divide a by b
  • floor(a / b) * b is the amount that was successfully shared entirely
  • The total (a) minus what was shared equals the remainder of the division

Applied to the last example, this gives:

5 % 7 = 5 - floor(5 / 7) * 7 = 5

Modular Arithmetic

That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that its perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

Using modulus operator in for Loop with if statements - Java beginner

Do you mean something like this?

for(int i = 0; i < 10; i++)
{
if(i%4 == 0)
{
condition
}
else if(i%4 == 1)
{
condition
}
else if(i%4 == 2)
{
condition
}
else if(i%4 == 3)
{
condition
}
}

Remember to put it on paper if you're confused and loop through your head (as a beginner)

Explanation of 1 mod 3

The remainder in 1%3 refers to what remains of 1 (not 3) after you divide by 3. As you have already said, 3 goes into 1 zero times. So -- when you remove 0 multiples of 3 from 1, all of 1 remains. Thus 1 % 3 = 1.

Why does 2 mod 4 = 2?

Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.



Related Topics



Leave a reply



Submit