Wednesday, June 16, 2010

Odd Number

How do you find whether the given number is odd? Just have a look at below statement. Does it return true if you pass odd number?

(num % 2 == 1)

No, It doesn't. It doesn't return true for all cases even the given number is odd.
Do you know why? Why it will not return true for all cases?

Lets discuss.............

The integer holds positive and negative values. If you pass the negative odd number it will return false because num % 2 returns the negative value, so it will not meet the condition(-1 == 1). When you do any arithmetic operation the result will be assigned with sign(+/-). Please see the sample output at the end.

However, my expectation is to return true if it is an odd number doesn't matter whether it is an positive or negative value. How do you do it? Please have a look at below statement.

(num % 2 != 0)

The above statement will return true even if you pass the negative odd number.
Hence, you should ensure to consider the negative values also while doing this kind of operation.

Code Snippet:

int num = Integer.MAX_VALUE;
System.out.println("Using condition (num % 2 == 1).......");
System.out.printf("\tIs odd number(%d): %b\n", num, (num % 2 == 1));
num = Integer.MAX_VALUE + 2;
System.out.printf("\tIs odd number(%d): %b\n\n", num, (num % 2 == 1));

// So changing the condition to work on all cases
System.out.println("Using condition (num % 2 != 0).......");
System.out.printf("\tIs odd number(%d): %b\n", num, (num % 2 != 0));
num = Integer.MAX_VALUE;
System.out.printf("\tIs odd number(%d): %b\n", num, (num % 2 != 0));
num = Integer.MAX_VALUE-1;
System.out.printf("\tIs odd number(%d): %b\n\n", num, (num % 2 != 0));

Output:
Using condition (num % 2 == 1).......
Is odd number(2147483647): true
Is odd number(-2147483647): false

Using condition (num % 2 != 0).......
Is odd number(-2147483647): true
Is odd number(2147483647): true
Is odd number(2147483646): false