Determining if a variable is even or odd?

Hello. If I have a variable is a whole number, how can I set up and if statement to see of the variable is even or odd? such as:

if (TEST==odd ){something};
if (TEST==even){something else};

Thanks

1 Like

2 Answers

2

Use modulo operator

if(test%2==0) // Is even, because something divided by two without remainder is even, i.e 4/2 = 2, remainder 0
if(test%2==1) // Is odd, because something divided by two with a remainder of 1 is not even, i.e. 5/2 = 2, remainder 1

what if a dividend is negative? He said the variable is a whole number.

–

Then just use Mathf.Abs before.

–

Very simple, thanks. if(test%2==1||test%2==-1) Can I use this too?

–

Just use test%2==0 for even or test%2!=0 for uneven. However, this only works in this special case or if you want determine if a number is fully dividable through another number or not.

–

in the strange case anyone wanted to see if a float is odd or even, first I would cast it to an int. It makes more sense to me, but some people might still prefer the strange case in which a float is perfectly dividable.

–

Here’s a blog article which benchmarks quite a few ways to test if a number is odd or even.

Surprisingly, the fastest way appears to be the modulus % operator, even out performing the bitwise ampersand &, as follows:

for (int x = 0; x < NumberOfNumbers; x++)
{
        if (x % 2 == 0)
               total += 1; //even number
        else
               total -= 1; //odd number
} 

Definitely worth a read for those that are curious.