[Tutor] Finding even and odd numbers

taserian taserian at gmail.com
Wed Sep 19 15:47:03 CEST 2007


On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote:

> Hi guys,
>
> I have come across a bit of code to find if a group of numbers is odd or
> even.The code snippet is shown below:
>
> 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.


I'll respond more from a general programming point of view than as a Python
expert (far from it!).

You can always tell if a regular number is divisible by 10, by just looking
at the last digit; if it's a zero, it is, and if it's anything else, it
isn't. That's a property of the decimal (base 10) system.

The above snippet is taking advantage of a similar property of binary
numbers, which are base 2. What the above snippet is doing is checking to
see if that last digit is a 0 or not (asking "not n&1" is equivalent to
asking "n&0", since that digit can only be a 0 or 1). Since binary numbers
are base 2, any binary number that ends in a 0 is divisible by 2, analogous
to the decimal number example above.

The technique being used to determine the value of the last digit is a
bitwise-AND. It compares the binary digits in the representation of n with
the binary digits in the representation of 1 on a one-to-one positional
arrangement. If either number has a zero in a certain position, the result
will have a zero in that position as well; if both numbers have a 1 in that
position, the result will have a 1.

As an example, I'll represent 4 as a binary number:

100 (4 in binary)
001 (1 in binary)
---------
000 (Result of bitwise-AND)

and now using 5 as our input:

101 (5 in binary)
001 (1 in binary)
--------
001 (Result of bitwise-AND)

Since 1 represented in binary is all zeroes except for the last digit, the
only way to get anything different from 000 as a result is for the last
digit to be 1.

Hopefully this didn't confuse you anymore. Experts, feel free to chime in.

Tony R.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070919/95b319ee/attachment.htm 


More information about the Tutor mailing list