How to determinate a integer odd or even

N

Nicholas Paldino [.NET/C# MVP]

ad,

Simple:

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

Hope this helps.
 
M

Michael Klingensmith

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
 
L

Lebesgue

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 :) )
 
J

Jon Skeet [C# MVP]

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...
 
Joined
Oct 13, 2013
Messages
6
Reaction score
0
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.
 
Joined
Oct 13, 2013
Messages
6
Reaction score
0
The link is now:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top