Odd and Even

This is a well-known programming fact, but since it came up today and I had to double check the C# syntax:

If you have many iterations in a loop, and you want to know if the current number is odd or even, the easiest and most natural way to tell is probably the modulus operator. However, that requires division. Computers are faster at addition and multiplication than they are at subtraction and division. Bitwise operations are also faster and easier for the computer than division. Therefore, a bitwise AND to 1 is the faster and more efficient way to tell if a number is odd or even. C# example:

for (int i = 0; i < 100; i++)
     result = String.Format(“{0} is even”, i);
     if ((i & 1)==1)
          result =
String.Format(“{0} is odd”, i);


No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: