Is that even?
Sirppi
Posted on January 27, 2024
Parity checking is one of the things you learn from elementary school or something. How complex can it be?
Lets lay out some facts to help us define what an even number is.
A number is even IF and ONLY IF ...
you divide by two and there's no residue
In C-like languages, you have the modulus operator to chip away and find the residue(remainder) of a division.
isEven(x) = x % 2 == 0
But people say modulus operator is kind of expensive. Keep that in the back of your mind.
This fact can also be implemented as recursive or iterative subtraction like this.
isEven(0) = true
isEven(1) = false
isEven(x) = isEven(x - 2)
The last binary digit is zero
The last binary digit can be obtained by AND-masking the number with 1
isEven(x) = x & 1 == 0
We could extend this "last digit property" to pretty much all the bases which are greater than 1 (I'm not sure about the negative and irrational bases... lol)
For example,
For a number to be even, the last decimal digit can be 0, 2, 4, 6 or 8 .
Halving results in an integer
Obvious. Right?
isEven(x) = x / 2 == floor(x / 2)
Integer-dividing it by two and doubling results in the original number
When you halve an odd number, you'll end up with residue which would be cleaned up by the floor function. Hence doubling won't restore the original number. If it was an even number, this wouldn't have been the case.
isEven(x) = floor(x / 2) * 2 == x
Adding one ONLY affects the last bit
Here's something cool. Because adding one to an even number ONLY affects the last bit since it would be zero to nicely hold in the new one. XOR could detect changes(inequalities) in data. So, the XOR of an even number and it's successor results in 1.
isEven(x) = x ^ (x + 1) == 1
Gcd of it and 2 is 2
The biggest number that could factor into 2 and an even number is always 2. Using this useful fact,
isEven(x) = gcd(x, 2) == 2
To sum up
I've listed half a dozen approaches to check the parity of a number.
My personal favourite is the x & 1 == 0
But if I want to do it in StYle, I'll go with x ^ (x + 1) == 1
Why did I do it? Nobody knows. C'mon it's MY blog article. I'll write whatever comes to MY mind.
:)
Posted on January 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.