programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# What are some of the best ways to test whether user input is either an odd or even number?

Ranch Hand
Posts: 121
2
For checking for Odd number I have this:

For even numbers I have:

Is there a cleaner/more efficient way of doing this?

Thank you

Bartender
Posts: 585
9
will test for odd, not even.

Sheriff
Posts: 23263
46
The "x modulo 2 is zero if and only if x is even" idea is the simplest way to do it, if you want other programmers who you haven't met yet to understand it. So that's how I would always do it.

However if you are comfortable with bit-fiddling you can start with the fact that numbers whose least significant bit is zero are always even. So a modified version of your code might look like:

This might even be faster, since integer division takes longer than a simple bit calculation. But only by a tiny amount, and it's not impossible that the run-time might optimize division by 2 into a bit calculation. I wouldn't even consider that code unless I expected my application to be spending most of its time deciding whether numbers were even or not, because I find it a lot less readable.

Marshal
Posts: 57437
175

Justin Robbins wrote:. . . . . .

That will not test for odd numbers. It will only find positive odd numbers. Use Paul C's suggestion; it will definitely run faster than the % operator. But it only works if you are trying to divide by exact powers of 2.

 Can't .... do .... plaid .... So I did this tiny ad instead: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS