How to find odd and even numbers in C#
There are 2 methods find even or odd numbers in C#.
Method 1: Modulus operator %
Method 2: BitField Operator &
Method 1: Modulus Operator %
Note:Find even or odd with modulus operator,When divided by 2 if remainder of the number is 0, then number is even otherwise odd.
for number 3 remainder is 1 so odd 3%2=1
for number 4 remainder is 0 so even. 4 %2=0
public bool isEven(int num)
{
if (num % 2 == 0) return true;
else return false;
}
{
if (num % 2 == 0) return true;
else return false;
}
Method 2: BitField Operator &
public bool isEvenUsingBitFields(Int32 num)
{
if ((num & 1) ==0) return true;
else return false;
}
Nice, easy, simple example with even simpler code to understand. Thank you! It would be great if more people wrote technical article in this simplistic fashion!
ReplyDeleteFor those who are more curious, this article examines the fastest way to get the remainder between using modulus or an alternative with addition:
http://blogs.davelozinski.com/curiousconsultant/csharp-net-use-the-modulus-operator-or-alternative
It’s obviously more for speed and micro-optimization junkies.
:-)
_
Here’s a blog article which benchmarks quite a few ways to test if a number is odd or even:
ReplyDeletehttp://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 other than the two you have listed. 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.
See this video which explains in a demonstrative manner https://www.facebook.com/photo.php?v=775812235793055
ReplyDelete