2

// check for a number is even or odd without / or % operator.

public class EvenOrOdd {

    public static int CheckEvenOrOdd(int num) {
        if (num > 2) {
            int number = num - 2;
            num = CheckEvenOrOdd(number);
        }
        return num;
    }

    public static void main(String[] args) {
        int num = CheckEvenOrOdd(5322221);
        if (num == 1) {
            System.out.println("Odd number");
        } else {
            System.out.println("Even number");
        }
    }

}

I defined stack size to 200m as -xss200m but this program turn up with OutOfMemory error and StackOverflow error if number is greater then 5322221.

Advise how to solve this problem to find the number is even or odd.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
Lalit Gupta
  • 21
  • 1
  • 2
  • 3
    You could avoid the memory problems, using your current implementation, by changing it from being recursive to being iterative. Also, consider the bitwise operators. – Patricia Shanahan Feb 17 '13 at 16:51
  • 2
    You can use `& 1` to check if it is even or odd. [There was a question about this recently](http://stackoverflow.com/questions/14905643/what-does-this-boolean-return-mean/14905686#14905686) – Martin Smith Feb 17 '13 at 16:51
  • you can implement - if ( (number % 2) == 0) { System.out.println("Even number"); } else { System.out.println("Odd number"); } – user1428716 Feb 17 '13 at 16:55

2 Answers2

16

You can use a fact that every odd number have 1 at the end of its binary representation so it looks like ???????1 where ? can be either 0 or 1. Here is how you can check it with binary AND -> &

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

It works like this:

for odd numbers

          ????????1 -> any odd number
          000000001 -> one
AND       ---------
result    000000001 -> one

for even numbers

          ????????0 -> any even number
          000000001 -> one
AND       ---------
result    000000000 -> zero
Pshemo
  • 122,468
  • 25
  • 185
  • 269
3

I asked a similar question a day or two ago. Look at this post: What does this boolean return mean?

Effectively, using this notation:

private static boolean isEven(int number)
{
    return (number & 1) == 0;
}

The & is a bitwise operator. More information on them can be found here: Bitwise Operators

Community
  • 1
  • 1
Andrew Martin
  • 5,619
  • 10
  • 54
  • 92