C++ program to find the Parity of a number efficiently

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find the parity of a given number N.

Parity is defined as the number of set bits (number of ‘1’s) in the binary representation of a number.

If the number of ‘1’s in the binary representation are even, the parity is called even parity and if the number of ‘1’s in the binary representation is odd, the parity is called odd parity.

If the given number is N, we can perform the following operations.

• y = N ^ (N >> 1)
• y = y ^ (y >> 2)
• y = y ^ (y >> 4)
• y = y ^ (y >> 8)
• y = y ^ (y >> 16)

Once all these operations are done, the rightmost bit in y will represent the parity of the number. If the bit is 1, the parity would be odd and if the bit would be 0, the parity will be even.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool calc_parity(int N) {
int y;
y= N ^ (N >> 1);
y = y ^ (y >> 2);
y = y ^ (y >> 4);
y = y ^ (y >> 8);
y = y ^ (y >> 16);
//checking the rightmost bit
if (y & 1)
return 1;
return 0;
}
int main() {
int n=1345;
int result = calc_parity(n);
if(result==1)
cout << "Odd Parity" << endl;
else
cout << "Even Parity" << endl;
return 0;
}

Even Parity