Thread: Odd And Even
View Single Post
Old 10-27-2004, 01:17 PM   #2 (permalink)
Belisarius
Java fanboy
 
Belisarius's Avatar
 
Join Date: Aug 2003
Posts: 1,175
Belisarius is on a distinguished road
That's one of those things in Java I never found out if there was a good way of doing it. It's kinda odd that Integer or Math doesn't have an even/odd method. But even so, this is pretty a basic computer science/math problem, so there are probably a million different ways to do it.

I'm assuming we're working with integers here. The result of any mathematical operation that has a fraction/decimal will have the partial number chopped off, not rounded (good thing in this case). As a result, you can do something like this:

Code:
int a = 15;
int b = a \ 2; // Might want to idiot check me on the divide symbol.
if ( (b * 2) == a ){
  // It's even
}else{
  // It's odd
}
The result of this is that b will equal 7, because the .5 gets chopped off. Because 7 * 2 != 15, we know it's odd.
__________________
GitS
Belisarius is offline   Reply With Quote