Odd and Even Numbers
July 13th, 2006
Sometimes its necessary to find out whether a number is odd or even. When I initially hit upon the problem, my immediate thought was to use the modulus function % and inspect the result.
However, a quick look at the PHP Manual showed a much easier way of determining whether a number is odd or even:
-
$status = (1 & $number) ? 'Odd' : 'Even';
The '&' sign represents the bitwise 'AND' operator, and the appropriate user comment explains:
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.
So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).
It's nice little tips like these found in PHP keeps me going throughout the day!
Add to del.icio.us
Digg this
Technorati
Related Posts:
Entry Filed under: PHP
4 Comments Add your own
1. Paul Scott | April 21st, 2007 at 2:40 pm
It may be slightly faster due to it being a bitwise operation, but how is it easier?
2. Paul Scott | April 21st, 2007 at 2:41 pm
The php was taken out.
$status = ($number % 2) ? 'Odd' : 'Even';
3. Leandro Vieira Pinho´s B&hellip | June 1st, 2007 at 3:04 pm
[…] Leia o original Odd and Even Numbers […]
4. leu | October 16th, 2007 at 2:19 pm
cheers this is just what i needed, tah
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed