Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

thedollarhunter

macrumors member
Original poster
May 9, 2011
80
0
UK
Any ideas on the simplest way to test if an integer is odd or even?

I want to be able to do something like this:

Code:
if(isEven(someVar)==1){
//...
}else{
//...
}

There must be something built into C++ :confused: or do I need to have a little divide by 2 into float and check it kind of function?
 
Don't need C++. Or even Objective-C. The plain old modulo operator in C is all you need (%).

Code:
if ((anInteger % 2) == 0 )
{
  // Even
}
else
{
 // Odd
}
 
Use modulo 2.

Code:
if (num%2)
{
//The number is odd.
}

else
{
//The number is even.
}

Edit: Robbie beat me to it.

Anyways, if you don't know what modulo is, it's just an operation that divides the first number by the second number and tells you what the remainder is. You use it by typing a percent sign, %. So if you take odd%2, the remainder will be 1, thus odd%2 is true, whereas if you take even%2, the remainder will be 0, thus even%2 is false.

Here's the wikipedia page on modulo:
http://en.wikipedia.org/wiki/Modulo_operator
 
Perfect and thanks for the speedy posts.

I found (random() % 6) really useful which I guess (with my feable understanding of math) is the same operation but used a different way?

Don't need C++. Or even Objective-C. The plain old modulo operator in C is all you need (%).

Code:
if ((anInteger % 2) == 0 )
{
  // Even
}
else
{
 // Odd
}
 
Another trick that should work is to just check if the rightmost bit is set to zero or one.

Code:
if (integer & 1)
{
    NSLog(@"ODD");
}
else
{
    NSLog(@"EVEN");
}

though this might not always work if you are dealing with integers less than zero.
 
I found (random() % 6) really useful which I guess (with my feable understanding of math) is the same operation but used a different way?

random() returns a random number, %6 would take the random number, divide it by 6, and tell you what the remainder is.

if random() returns... then random()%6 is...
0... 0
1... 1
2... 2
3... 3
4... 4
5... 5
6... 0
7... 1
8... 2
9... 3
10... 4
11... 5
12... 0
13... 1

and so on. Thus random()%6 returns a random integer between 0 and 5.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.