CHECK A NUMBER IS EVEN OR ODD MORE EFFICIENTLY

We all know if a number is divisible by two that is an even number else odd. But in computer divide is not an easy task, it comes up with a cost.

We know, computer works with bits so if we can convert this odd, even check using bits that will be faster than our common method. Look carefully the following numbers.

Look how the last bit is changed, for every odd number the last bit is always one and for even its zero. Using this pattern we can check if a number is odd or even. Here we will use bitwise operator & (and), we know when both bit is one the answer is one else zero. So if we and with one with an odd number the answer will be always one else zero if the number is even.
Java implementation of this method is,

// this method returns true if odd
public static boolean isOdd(int i) {

    return (i & 1) == 1;

}


Binary representation of 6 (even) is 110 and 1 is 001
6 & 1 = 110 & 001 = 000
Binary representation of 7 (odd) and 1 is 001
7 & 1 = 111 & 001 = 001

S. Mahbub – Uz – Zaman
Monday, September 12, 2011

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s