Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Justin Robbins
Ranch Hand
Posts: 121
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For checking for Odd number I have this:


For even numbers I have:



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


please explain
Thank you
 
Fred Kleinschmidt
Bartender
Posts: 560
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
will test for odd, not even.
 
Paul Clapham
Sheriff
Posts: 22487
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55715
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!