Finding the Parity of a number Efficiently in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the parity of a number.

We can find the parity of a number efficiently by performing the following operations using xor and right-shift operators.

int b;
b = n ^ (n >> 1);
b = b ^ (b >> 2);
b = b ^ (b >> 4);
b = b ^ (b >> 8);
b = b ^ (b >> 16);

If the last bit of the result is 1 then it's an odd parity else even parity.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findParity(int n) {
   int b;
   b = n ^ (n >> 1);
   b = b ^ (b >> 2);
   b = b ^ (b >> 4);
   b = b ^ (b >> 8);
   b = b ^ (b >> 16);
   if ((b & 1) == 0) {
      cout << "Even Parity" << endl;
   }
   else {
      cout << "Odd Parity" << endl;
   }
}
int main() {
   int n = 15;
   findParity(n);
   return 0;
}

Output

If you run the above code, then you will get the following result.

Even Parity

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 15:30:50
Advertisements