[Tutor] Finding even and odd numbers

Terry Carroll carroll at tjc.com
Wed Sep 19 22:16:58 CEST 2007


On Wed, 19 Sep 2007, Boykie Mackay wrote:

> if not n&1:
>     return false
> 
> The above should return false for all even numbers,numbers being
> represented by n.I have tried to wrap my head around the 'not n&1' but
> I'm failing to understand what's going on.Could someone please explain
> the statement.

Others have explained why this works, but let me rail against this code 
for a moment.  IMHO, a bitwise operation is appropriate only when the 
field being operated on is a set of bits with bitwise information; for 
example, if the right-most bit was a flag bit of some sort, N&1 is a 
perfectly appropriate operation.

But evenness/oddness is a property of numbers, and the code would be much 
easier to understand if the parameter was treated as a number, rather than 
as a field of bits, i.e.:

>>> def isodd(n):
...  return bool(n%2)
...
>>> isodd(4)
False
>>> isodd(7)
True
>>>

Mind you, I'll bet that the bit-checking method is slightly faster than
the modulus operation in my little piece of code above.  I'll also bet
that, if you added up the amount of time that was saved by using the
bitwise approach over the modulus approach, over all executions of the
program everywhere, it probably would be a smaller amount of time than it
would take for a programmmer maintaining the program to find out what that
line of code is supposed to do.

</soapbox>



More information about the Tutor mailing list