Recipe1.5.Testing for an Even or Odd Value


Recipe 1.5. Testing for an Even or Odd Value

Problem

You need a simple method to test a numeric value to determine whether it is even or odd.

Solution

The solution is actually implemented as two methods. To test for an even integer value, use the following method:

 public static bool IsEven(int intValue) {     return ((intValue % 2) == 0); } 

To test for an odd integer value, use the following method:

 public static bool IsOdd(int intValue) {     return ((intValue % 2) == 1); } 

Discussion

Every odd number always has its least-significant bit set to 1. Therefore, by checking whether this bit is equal to 1, you can tell whether it is an odd number. Conversely, testing the least-significant bit to see whether it is 0 can tell you whether it is an even number.

To test whether a value is even, you AND the value in question with 1 and then determine whether the result is equal to zero. If it is, you know that the value is an even number; otherwise, the value is odd. This operation is part of the IsEven method.

On the other hand, you can determine whether a value is odd by ANDing the value with 1, similar to how the even test operates, and then determine whether the result is 1. If so, you know that the value is an odd number; otherwise, the value is even. This operation is part of the IsOdd method.

Note that you do not have to implement both the IsEven and IsOdd methods in your application, although implementing both methods might improve the readability of your code. You can implement one in terms of the other. For example, here is an implementation of IsOdd in terms of IsEven:

 public static bool IsOdd(int intValue) {     return (!IsEven(intValue)); } 

The methods presented here accept only 32-bit integer values. To allow this method to accept other numeric data types, you can simply overload it to accept any other data types that you require. For example, if you need to also determine whether a 64-bit integer is even, you can modify the IsEven method as follows:

 public static bool IsEven(long longValue) {     return ((longValue & 1) == 0); } 

Only the data type in the parameter list needs to be modified.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net