Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether a number is even or odd using C#?

Tags:

syntax

c#

I know that there is already a way to find if a number is even or odd using the modulus (What is the fastest way to find if a number is even or odd?) however I was wondering if there is a C# function like Math.Even or Math.Odd. Is the only way to do this by using a modulus?

(I know this sounds like a stupid question, but I bet my teacher that there was a built in feature to do this in C#, he claims there isn't....)

like image 727
Ian Wise Avatar asked Dec 15 '14 16:12

Ian Wise


3 Answers

It may count as cheating, but if you use BigInteger, it has an IsEven method.

As stated in MSDN, calling this method is equivalent to:

value % 2 == 0;

Reference:

  • http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.iseven(v=vs.110).aspx
like image 92
Neolisk Avatar answered Nov 08 '22 12:11

Neolisk


There is no method in .NET that just calls %2==0 for you. Such a simple method presumably isn't worth their time to implement for you, given that the alternative is literally five characters.

You can of course write your own named method to perform this calculation if you really want to.

like image 23
Servy Avatar answered Nov 08 '22 10:11

Servy


Actually, there are more interesting points, and some other methods to check is number even. When you use %, you should check your values with 0 as was mentioned by others, because comparing with 1 will give the wrong answer with all negative integers.

bool is_odd(int n) {
    return n % 2 == 1; // this method is incorrect for negative numbers
}
bool is_odd(int n) {
    return n % 2 != 0;
}

The second popular way is demonstrated below

bool is_odd(int n) {
    return x & 1 != 0;
}

This method makes use of the fact that the low bit will always be set on an odd number.

Many people tend to think that checking the first bit of the number is faster, but that is not true for C# (at least). The speed is almost the same and often modulus works even faster.
There is the article where the author tried out all popular ways to check if the number is even and I recommend you to look at the tables that are demonstrated at the bottom of the article.

like image 35
Vitalii Isaenko Avatar answered Nov 08 '22 10:11

Vitalii Isaenko