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?
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:
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.
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.
%2==0
. It's 5 characters, not 2. This is 2.5 times more complicated ;) –
Ruhl Using (myVal % 2) == 0
is good, but bitwise operators are fast too:
(myVal & 0x1) == 0
Works for positive and negative values, and different types (e.g. 16-bit or 64-bit).
things changed for generic math.
int.IsEvenInteger(x)
(implemented by System.Int32)
© 2022 - 2024 — McMap. All rights reserved.