I've always used the following in order to find even and odd numbers:
if( $num % 2 ) { echo "odd"; }
if( !($num % 2) ) { echo "even"; }
But recently I stumbled upon with the following code that works exactly the same:
if( $num & 1 ) { echo "odd"; }
if( !($num & 1) ) { echo "even; }
What's the logic behind the "&" in the second method?
I went to check the PHP: Arithmetic Operators and the ampersand is not part of the options.
Thanks.
Even numbers are divisible by 2 without remainders. They end in 0, 2, 4, 6, or 8. Odd numbers are not evenly divisible by 2 and end in 1, 3, 5, 7, or 9. You can tell whether a number is odd or even regardless of how many digits it has by looking at the final digit.
To tell whether a number is even or odd, look at the number in the ones place. That single number will tell you whether the entire number is odd or even. An even number ends in 0, 2, 4, 6, or 8. An odd number ends in 1, 3, 5, 7, or 9.
The product of two or more odd numbers is always odd. 3. The sum of an even number of odd numbers is even, while the sum of an odd number of odd numbers is odd. For instance, the sum of the four odd numbers 9, 13, 21 and 17 is 60, while the sum of five odd numbers 7, 15, 19, 23 and 29 is 93.
It is the bitwise-AND operator. Remember that in the computer, every integer is stored in binary form, and the lowest-significance binary digit is 2^0 == 1. So, every odd number will have the lowest binary digit = 1.
So, the bitwise AND operator compares your value bit-by-bit with the constant 1
. Bits that are 1
in both operands are set to 1
in the result, but bits that are 0
in either operand are set to 0
in the result. The final result (which will be either 1
or 0
) is coerced to boolean by PHP because you are using it as the clause in an if()
statement.
There is a very good reason for checking evenness with &
instead of %
: Speed! The %
operator requires a division operation so the remainder can be calculated, which is computationally much, much more expensive than just comparing the bits directly.
An example:
$num = 9; // 9 == 8 + 1 == 2^3 + 2^0 == 1001b
echo (string)($num & 1); // 1001b & 0001b = 0001b - prints '1'
$num = 10; // 10 == 8 + 2 == 2^3 + 2^1 == 1010b
echo (string)($num & 1); // 1010b & 0001b = 0000b - prints '0'
&
is the binary AND
.
The binary value of an odd number AND 1 will be 1, and the binary value of an even number AND 1 will be 0.
This happens because the binary value of an odd number always ends with 1 and the binary value of an even number ends with 0. So...
10101101 & 00000001 = 00000001
in the case of an odd number and,
10101100 & 00000000 = 00000000
in the case of an even number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With