Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct way to determine if two numbers have the same parity?

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?

like image 480
Tudor Gălățan Avatar asked Nov 22 '17 21:11

Tudor Gălățan


People also ask

How do you know if two numbers have the same parity?

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).

What does it mean for two numbers to have the same parity?

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.

What is the parity of?

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.

How many odd natural numbers have the same parity as their Factorials?

Answer - 0 is the odd natural number which have same parity !


1 Answers

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.

like image 54
Michaël Roy Avatar answered Oct 13 '22 01:10

Michaël Roy