How to determinate a integer odd or even

  • Thread starter Thread starter ad
  • Start date Start date
ad,

Simple:

// See if integer i is odd or even:
bool even = ((i % 2) == 0);

Hope this helps.
 
You can determine this by using the modulo operator %

int i = 1;
bool isEven = (i % 2 == 0);
isEven will be false

int i = 2;
bool isEven = (i % 2 == 0);
isEven will be true meaning it is even.

Michael Klingensmith
http://www.seeknsnatch.com
 
Jon Skeet said:
boolean even = ((x & 1)==0);

He asked about C#, not Java, Jon ;-) (OK, I know you are writing much more
code in Java than in C# these days :-) )
 
Lebesgue said:
He asked about C#, not Java, Jon ;-) (OK, I know you are writing much more
code in Java than in C# these days :-) )

Doh :)

bool even = ((x&1)==0);

It's worth knowing the &1 instead of %2 trick, for the occasional
performance-intensive bit of code. It can make quite a difference...
 
Here’s a blog article which benchmarks quite a few ways to test if a number is odd or even:
blogs ^ davelozinski ^ com/curiousconsultant/csharp-net-fastest-way-to-check-if-a-number-is-odd-or-even


There are actually numerous ways to do this. Surprisingly, the fastest way appears to be the modulus % operator, even out performing the bitwise ampersand &, as follows:

if (x % 2 == 0)
total += 1; //even number
else
total -= 1; //odd number

Definitely worth a read for those that are curious.
 
The link is now:

cc davelozinski com/c-sharp/fastest-way-to-check-if-a-number-is-odd-or-even
 
Back
Top