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....)
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With