6

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?

1 Answers1

8

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.

Michaël Roy
  • 6,338
  • 1
  • 15
  • 19