158

How would I determine whether a given number is even or odd? I've been wanting to figure this out for a long time now and haven't gotten anywhere.

Flexo
  • 87,323
  • 22
  • 191
  • 272
Josh
  • 1,639
  • 2
  • 11
  • 3

16 Answers16

233

You can use the modulus operator, but that can be slow. If it's an integer, you can do:

if ( (x & 1) == 0 ) { even... } else { odd... }

This is because the low bit will always be set on an odd number.

Snekse
  • 15,474
  • 10
  • 62
  • 77
lucasmo
  • 5,884
  • 4
  • 22
  • 17
  • 29
    It still amazes me that people prefer modulus over simply checking the first bit of the number. Obviously if the first bit is set, then the number must be odd. It's usually faster, and it reads just as well in my opinion. I think the reason others don't prefer it over modulus comes down to a lack of understanding of binary. – crush Feb 13 '14 at 21:47
  • 2
    @crush The compiler/JVM is (probably) smart enough to optimize `N % 2`. Premature optimization is the root of all evil... – dtech May 05 '14 at 09:22
  • 5
    @dtech I think you misunderstand the meaning of premature optimization. If you know beforehand that one method is more performant than another, then it's not premature optimization to use the more performant method. It's intelligent. That said, my comment was more about how checking the first bit is more logical than using modulus when simply checking for even/odd. The problem is that many programmers don't understand what either method does, and just follow tutorials. – crush May 05 '14 at 11:27
  • 74
    @crush `n % 2 == 0` semantically means `Divide by 2 and check if the remainder is 0`, which is much clearer than `n & 1 == 0` which means `Zero all the bits but leave the least significant bit unchanged and check if the result is 0`. The improved clarity of the first is worth the (probably non-existant) overhead. That is what I meant with premature optimization. If something is slow and you profile it in that part changing `n % 2` to `n & 1` is certainly justified, but doing it beforehand isn't. In general working with the bit operators is a bad idea before profiling. – dtech May 05 '14 at 12:36
  • 19
    @dtech First of all, your opinion is completely subjective. Second of all, you still don't understand what "premature optimization" means. It is a micro optimization, sure. It's not a premature optimization. Premature optimization is revising existing code with "optimizations" without first profiling the existing code to see that it is inefficient. However, knowing beforehand that writing code one way vs. another way is more efficient, and choosing to use the more efficient code, is NOT premature optimization. It is your subjective opinion that `n % 2 == 0` is *cleaner* than `n & 1 == 0`. – crush May 05 '14 at 13:49
  • 2
    @dtech Anyone with an understanding of base 2 would understand quite clearly that `n & 1 == 0` is checking for even. I like how you tried really hard to make `n & 1 == 0` sound much more complex and obtuse than it really is. Let's be honest. `n & 1 == 0` Is doing a bitwise AND on the first bit. Where modulus shines is when you have `x % n` scenarios. – crush May 05 '14 at 14:02
  • 4
    @dtech Never _assume_ that your compiler is smarter than you. Because as it turns out, in this case, it isn't. If you actually look through the assembly, a bit check in this scenario requires less instructions than a mod check. See top answer & comments here >>> http://stackoverflow.com/questions/16969220/what-is-the-most-efficent-way-to-detect-even-numbers-in-java – arkon Aug 13 '14 at 18:47
  • 5
    If optimization is that important, let's all go back to C. Runs about 40x faster than Java... And we can again do everything JAVA does for us, ourselves :-) Sorry guys don't kill me had to say this :-) – Lawrence Sep 01 '14 at 09:30
  • 1
    @Lawrence - ... that's ~exactly~ why C is still use A TON today. No one needs to go "back" when we're still here using C for the reason you stated yourself :P – user99999991 Sep 22 '14 at 05:38
  • 4
    funny, top voted answer with 41 upvotes and it doesn't even compile. – eis Nov 21 '14 at 06:54
  • 1
    @Lawrence except that it doesn't. For some programs, C is faster, for some Java. The difference tends to be around 10-20%, hardly 40x of anything. – eis Nov 21 '14 at 07:00
  • 23
    I'd just like to point out for people coming here that using the modulo operator is fine, but if you're using it to test oddness, write n % 2 != 0, not n % 2 == 1, because the latter doesn't work for negative numbers in Java. – Jxek Jan 08 '15 at 09:38
  • Guys why you are assuming that applying and operator to any number with 1 will produce 0 if even? Say 4 & 1, 00000100 & 00000001 = 11111010, so not 0 – Grigor Nazaryan May 05 '16 at 23:34
  • @eis, I think you are mixing C++ with C. C++ is about 10-20% faster than JAVA. And C is another 10 to 20% faster than C++ :-D Not that it matters, I prefer JAVA anyway but if we're bit-screwing anyway.. haha :-) I still have to encounter the first JAVA program that beats C in performance. Stability is another issue where skills will be more important. To write a stable C program requires better dev skills I feel. No insult intended... – Lawrence Jun 22 '16 at 15:41
  • 2
    @Lawrence If you haven't seen any, I guess you haven't looked at the actual benchmarks like [this](http://scribblethink.org/Computer/javaCbenchmark.html), combining several results. Despite the title it quotes several C examples. – eis Jun 22 '16 at 21:48
  • @GrigorNazaryan Check your binary function. The 00000100 & 00000001 = 00000000. You were doing a 'nor' see https://en.wikipedia.org/wiki/NOR_gate. – The Coordinator Oct 15 '16 at 23:46
  • @dtech Re 'premature optimization', I suggest you look up what Knuth actually wrote. You will get quite a surprise. This is one of the most persistently misused partial quotations in computer science. – user207421 Apr 12 '17 at 00:05
  • Just for fun I did a little benchmarking: I tested with a stream of 1.000.000.000 ints (JDK 8_131 64bit) on my windows machine. I got an average difference of about 500 milliseconds, that means a performance gain of 0.5 nanoseconds per operation. So be careful, using modulo will really slow down your application! ;-) That's a pitty, then IMHO the modulo variant is more readable. – Volker Seibt May 24 '17 at 09:23
  • JMH Benchmark: `and1: 2146187,616 ops/s mod2: 1347458,546 ops/s` – Matej Kormuth Jun 22 '17 at 21:19
  • So bitwise check actually wins. i guess if the code will be shown to smart people only, then bitwise checking will be the choice since it is a programming ABC that every programmer familiar of. Otherwise, use % 2. – RaymondM Jan 29 '18 at 04:01
  • How about 0 ? In this case 0 would be even ( (x & 1) == 0 is true ). Is it possible to rewrite condition so it would consider 0 odd? (Other then writing new if statement). – Sergii Aug 03 '22 at 12:52
  • I like this option. Unfortunately some code reviews will punish this approach for "lack of readability" by people unfamiliar or forgetful of bitwise operations so there is also something to be said for doing as the Romans do. – Meadowlark Bradsher Dec 07 '22 at 23:39
122
if ((x % 2) == 0) {
   // even
} else {
   // odd
}
RubioRic
  • 2,442
  • 4
  • 28
  • 35
poy
  • 10,063
  • 9
  • 49
  • 74
31

If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • 15
    The % operator is called modulo. – Anthony Sep 08 '11 at 01:37
  • 4
    @Anthony: Actually, it's the ["remainder operator"](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3). – Ryan Stewart Sep 08 '11 at 01:41
  • 4
    The mathematical term is modulus, and it has wider-applicability than getting the remainder. `(A % B)` itself can be used as an expression, and that's when things get fun. – Stefan Kendall Sep 08 '11 at 01:59
  • 2
    @Stefan: I won't belabor the point, but mathematicians tend to point out that in [modular arithmetic](http://en.wikipedia.org/wiki/Modular_arithmetic) the modulus and the remainder [aren't the same thing](http://mathforum.org/library/drmath/view/54363.html). – Ryan Stewart Sep 08 '11 at 02:07
  • Google "modulus operator" (language). Correct the few thousand results and I'll reconsider my comment. – Stefan Kendall Sep 08 '11 at 03:30
  • 2
    @StefanKendall Check the [Java Language Specification #15.17.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3). Google is not a normative reference. – user207421 Apr 12 '17 at 00:06
  • `%` is very slow. Use the bit operation instead, as the comment bellow – Happy Aug 18 '21 at 07:10
26

The remainder operator, %, will give you the remainder after dividing by a number.

So n % 2 == 0 will be true if n is even and false if n is odd.

user207421
  • 305,947
  • 44
  • 307
  • 483
Phil
  • 706
  • 5
  • 6
23

Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the % (modulo) operator, which divides the number on the left by the number on the right and returns the remainder...

boolean isEven(double num) { return ((num % 2) == 0); }
Naveen Kumar M
  • 7,497
  • 7
  • 60
  • 74
fireshadow52
  • 6,298
  • 2
  • 30
  • 46
  • 1
    'Regardless of if it's a decimal' is meaningless. Decimal is a radix. Do you mean 'contains a fractional part'? – user207421 Apr 12 '17 at 00:07
8

I would recommend

Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch and Neal Gafter

There is a briefly explanation how to check if number is odd. First try is something similar what @AseemYadav tried:

public static boolean isOdd(int i) {
     return i % 2 == 1;
}

but as was mentioned in book:

when the remainder operation returns a nonzero result, it has the same sign as its left operand

so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use @Camilo solution or just do:

public static boolean isOdd(int i) {
     return i % 2 != 0;
}

but generally the fastest solution is using AND operator like @lucasmo write above:

public static boolean isOdd(int i) {
     return (i & 1) != 0;
}

@Edit It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative

Michu93
  • 5,058
  • 7
  • 47
  • 80
4

Least significant bit (rightmost) can be used to check if the number is even or odd. For all Odd numbers, rightmost bit is always 1 in binary representation.

public static boolean checkOdd(long number){
   return ((number & 0x1) == 1);
}
3

Works for positive or negative numbers

int start = -3;
int end = 6;

for (int val = start; val < end; val++)
{
    // Condition to Check Even, Not condition (!) will give Odd number
    if (val % 2 == 0) 
    {
        System.out.println("Even" + val);
    }
    else
    {
        System.out.println("Odd" + val);
    }
}
RamenChef
  • 5,557
  • 11
  • 31
  • 43
Kiran G
  • 31
  • 2
2

This following program can handle large numbers ( number of digits greater than 20 )

package com.isEven.java;
import java.util.Scanner;

public class isEvenValuate{

public static void main(String[] args) {            

        Scanner in = new Scanner(System.in);
        String digit = in.next();

        int y = Character.getNumericValue(digit.charAt(digit.length()-1));

        boolean isEven = (y&1)==0;

        if(isEven)
            System.out.println("Even");
        else
            System.out.println("Odd");

    }
}

Here is the output ::

  122873215981652362153862153872138721637272
  Even
Community
  • 1
  • 1
2

If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:

public void evenOrOddNumber(int number) {
  if (number % 2 == 0) {
    System.out.println("Number is Even");
   } else {
    System.out.println("Number is odd");
  }
 }
corneliouz Bett
  • 149
  • 1
  • 10
2
    /**
     * Check if a number is even or not using modulus operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    /**
     * Check if a number is even or not using & operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEvenFaster(int number) {
        return (number & 1) == 0;
    }

source

duyuanchao
  • 3,863
  • 1
  • 25
  • 16
1

Another easy way to do it without using if/else condition (works for both positive and negative numbers):

int n = 8;
List<String> messages = Arrays.asList("even", "odd");

System.out.println(messages.get(Math.abs(n%2)));

For an Odd no., the expression will return '1' as remainder, giving

messages.get(1) = 'odd' and hence printing 'odd'

else, 'even' is printed when the expression comes up with result '0'

Aseem Yadav
  • 728
  • 7
  • 15
  • 1
    This question was tagged as JAVA. You posted an answer in Python. Not that useful really. – Mark Dec 04 '17 at 16:49
  • Hey @Mark ! Thanks for pointing that out, edited the answer. Hope, it can still be of any help to someone this time. – Aseem Yadav Dec 11 '17 at 14:30
  • 1
    It can be easily crashed for example by: `int n = -3;`. As @Camilo mentioned below - when the remainder operation return a nonzero result, it has the same sign as its left operand so generelly we have `System.out.println(messages.get(-1));` what gives us `java.lang.ArrayIndexOutOfBoundsException` – Michu93 Aug 23 '18 at 11:30
1

You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:

public static void main(String[] args) {        
    System.out.println("Enter a number to check if it is even or odd");        
    System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));        
}
1

You can do like this:

boolean is_odd(int n) {
    return n % 2 == 1 || n % 2 == -1;
}

This is because Java has in its modulo operation the sign of the dividend, the left side: n. So for negatives and positives dividends, the modulo has the sign of them.

Of course, the bitwise operation is faster and optimized, simply document the line of code with two or three short words, which does it for readability.

Michael Hoff
  • 6,119
  • 1
  • 14
  • 38
Camilo
  • 439
  • 5
  • 13
  • It is called the [remainder operator](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3), not the modulo operator. – user207421 Apr 30 '18 at 05:16
0
package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter number: ");
        int y = scan.nextInt();       
        boolean isEven = (y % 2 == 0) ? true : false;
        String x = (isEven) ? "even" : "odd";  
        System.out.println("Your number is " + x);
    }
}
Bob
  • 1
0

Here is full example:-

import java.text.ParseException;

public class TestOddEvenExample {
    public static void main(String args[]) throws ParseException {

        int x = 24;
        oddEvenChecker(x);

        int xx = 3;
        oddEvenChecker(xx);
    }

    static void oddEvenChecker(int x) {
        if (x % 2 == 0)
            System.out.println("You entered an even number." + x);
        else
            System.out.println("You entered an odd number." + x);
    }
}

enter image description here

Vipul Gulhane
  • 761
  • 11
  • 16