251

As an example in pseudocode:

if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}
sschuberth
  • 28,386
  • 6
  • 101
  • 146
Bob
  • 2,649
  • 2
  • 16
  • 6

17 Answers17

387

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;
axel22
  • 32,045
  • 9
  • 125
  • 137
Cody Hatch
  • 8,857
  • 6
  • 29
  • 36
  • 64
    Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative. – Jim Aug 24 '12 at 22:36
  • 1
    why is `a % 2` put in parenthesis before `== 0` is evaluated? – nl-x Jun 03 '14 at 19:09
  • 4
    @nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that `%` is evaluated before `==` before I looked it up, so it would be unclear whether the expression is equivalent to `(a%2)==0` or `a%(2==0)`. I guess it is less important in java where a boolean is not the same as an integer – Matthew Sainsbury Jun 06 '14 at 12:13
  • 9
    This isn't the modulus operator - it's the remainder operator. Please correct the post! – Kieren Johnstone Jul 17 '15 at 06:56
  • 2
    boolean even = ((a & 1) == 0). Much easier. – mdev Mar 11 '18 at 03:36
  • I my opinion the explicit if/else is easier on the eyes and faster to scan (would be even faster if opening brackets were on the same line as method signatures but after all that's personal preference). But we should not always go for "shortest" if it compromises readability (thinking of ternary operator-nesting). – Wolfone Jun 19 '18 at 06:09
111

Here is the representation of your pseudo-code in minimal Java code;

boolean isEven = a % 2 == 0;

I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
martinatime
  • 2,468
  • 1
  • 17
  • 23
  • 12
    minimal would be without the brackets ;) – pstanton Sep 28 '10 at 01:29
  • 4
    It's a remainder operator, not a modulus operator. – user207421 Mar 30 '16 at 01:51
  • @user207421 Its name is in fact [_remainder operator_](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) but aren't they equivalent: "[**modulus**](https://en.wiktionary.org/wiki/modulus#Noun) – 4. _(computing, programming)_ An operator placed between two numbers, to get the remainder of the division of those numbers."? – Gerold Broser May 09 '19 at 12:28
98

Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.

(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.

Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).

Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".

The first approach is good for beginners, because it is especially verbose.

// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
{
  isEven = true
}
else
{
  isEven = false
}

The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)

// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);

The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.

// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;

The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.

// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);

Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)

starball
  • 20,030
  • 7
  • 43
  • 238
Rob Rolnick
  • 8,519
  • 2
  • 28
  • 17
  • Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders. – Jim Aug 24 '12 at 22:12
  • 1
    @TickledPink Except that this does not compile in Java. – Evgeniy Berezovsky Nov 09 '19 at 01:51
  • Looking at [operator precedence](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html), option 4 can be reduced to `boolean isEven = (a & 1) == 0;` I also like to make it clear we're doing bit operations like so: `boolean isEven = (a & 0x1) == 0;` though that's a matter of taste ;-) – Hummeling Engineering BV Jan 08 '22 at 11:32
35

To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
    {
        result += y;
    }
    return result;
}

or with the ternary operator (shorter, but not possible or less efficient in some situations):

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}
Zom-B
  • 351
  • 3
  • 2
13

While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.

(a % b + b) % b

This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.

Note: If b is negative, the result will also be negative

Stefan T
  • 427
  • 4
  • 7
12

Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!

Greg Charles
  • 1,880
  • 4
  • 20
  • 39
  • But I want one a real modulo operator that works for negative integers too so that `array[x mod array.length]` allways accesses an element in my array rather than try to index negative positions. – Kris Nov 11 '19 at 04:19
  • 3
    `(x % y + y) % y` or starting in Java 8, `Math.floorMod(x, y)` – Greg Charles Nov 12 '19 at 19:11
11

The code runs much faster without using modulo:

public boolean isEven(int a){
    return ( (a & 1) == 0 );
}

public boolean isOdd(int a){
    return ( (a & 1) == 1 );
}
michael
  • 111
  • 1
  • 2
  • 3
    This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works. – AlexWien Jul 15 '13 at 19:39
  • 4
    @LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different. – user207421 Nov 17 '15 at 10:35
  • 3
    @EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and. – Lluis Martinez Nov 18 '15 at 00:43
  • Why would this be an answer? Sure it does odd even, but does not do anything with mod/remainder operator. The question talks about mod operator, not how to find odd even. – Mark Walsh Mar 24 '20 at 17:30
6

In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod​(int x, int y)

Roland
  • 7,525
  • 13
  • 61
  • 124
  • 2
    Upvoted, because floorMod is a better 'modulo' operator than `%` as it also works properly when the argument is negative as well. None of the other answers really are correct since they come with the disclaimer that % is not really modulo unless the arguments are positive. In particular if you want to map every integer to a consecutive position in an array then `array[floorMod(i, array.length)` works correctly even if the index `i` goes into negative territory. Not so with `%`. – Kris Nov 11 '19 at 04:23
6

As others have pointed out, the % (remainder) operator is not the same as the mathematical mod modulus operation/function.

mod vs %

The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).

In order to have a method to use the mathematical modulus operation and not care about the sign in front of x one can use:

((x % n) + n) % n

Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

enter image description here

m4110c
  • 427
  • 4
  • 10
  • 3
    Nice drawing. One other complexity: this doesn't take the 2^32 modularity of the `int` variable itself into account. The `floorMod` method does do that correctly (but you may need additional calculations if `n` is negative). – Maarten Bodewes May 05 '20 at 22:44
5
if (a % 2 == 0) {
} else {
}
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
J D OConal
  • 624
  • 4
  • 14
4

you should examine the specification before using 'remainder' operator % :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
    num %= 10;
    if(num == 1)
       return false;
    else if(num == 0)
       return true;
    else
       return isEven(num + 2);
}
isEven = isEven(a);
kioto
  • 93
  • 1
  • 4
3

The remainder operator in Java is % and the modulo operator can be expressed as

public int mod(int i, int j)
{
  int rem = i % j;
  if (j < 0 && rem > 0)
  {
    return rem + j;
  }
  if (j > 0 && rem < 0)
  {
    return rem + j;
  }
  return rem;
}
eljenso
  • 16,789
  • 6
  • 57
  • 63
3

Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
2

In Java, the mod operation can be performed as such:

Math.floorMod(a, b)

Note: The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:

a % b
Shant Dashjian
  • 888
  • 11
  • 20
  • Well not exactly... The javadoc of `Math.floorMod()` has it: `The floor modulus is x - (floorDiv(x, y) * y), has the same sign as the divisor y, and is in the range of -abs(y) < r < +abs(y).` So it is not exactly the same as mathematical modulus. **But**, there is a way to get a positive result, also in the Javadoc of the same method: `If the signs of arguments are unknown and a positive modulus is needed it can be computed as (floorMod(x, y) + abs(y)) % abs(y).` – WesternGun Jan 06 '20 at 22:13
  • @WesternGun That may be true, but **if** you know that the modulus is positive then the `floorMod` operation works as expected. There is also the `floorMod` for `long` values and otherwise there is `BigInteger` for larger values. – Maarten Bodewes May 05 '20 at 22:41
1

Another way is:

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

But easiest way is still:

boolean isEven = (a % 2) == 0;

Like @Steve Kuo said.

brothers28
  • 1,196
  • 17
  • 23
-1

The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).

jjrv
  • 4,211
  • 2
  • 40
  • 54
-3

An alternative to the code from @Cody:

Using the modulus operator:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven compensates.

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168