I found two solutions to find out if two numbers have the same parity (both are odd numbers or both are even). In C++, they look like this:
if ((a+b)%2 == 0)
and
if (a%2 == b%2)
The problem is that the first one works on 100% of cases and the second one only on 80% of the cases (the tests of a problem that I have submitted on a website) and I do not understand why. For me, both lines of code should work fine on all cases. Can somebody explain me why does the first line of code work in all cases and the second one does not? And which method (those showed by me or another) would you recommend?
The parity of an integer is its attribute of being even or odd. Thus, it can be said that 6 and 14 have the same parity (since both are even), whereas 7 and 12 have opposite parity (since 7 is odd and 12 is even).
If two integers are either both even or both odd, they are said to have the same parity; otherwise they have different parity. Determining the parity of two quantities is often a simple and useful way to prove that the quantities can never be equal.
Definition of parity 1 : the quality or state of being equal or equivalent Women have fought for parity with men in the workplace. 2a : equivalence of a commodity price expressed in one currency to its price expressed in another The two currencies are approaching parity for the first time in decades.
Answer - 0 is the odd natural number which have same parity !
I would not recommend either of the methods in your post, you should use one of these instead:
if ((a & 1) == (b & 1)) {} // this is clearer
if (((a ^ b) & 1) == 0) {} // this is faster
if (!((a ^ b) & 1)) {} // this is as fast as faster
These depend on the fact that bit 0 will be set for odd values, even if negative. Avoid integer division (and modulo) whenever possible, it's one of the slowest instructions on any CPU.
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