
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ program to find the Parity of a number efficiently
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
#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; }
Output
Even Parity
- Related Articles
- Finding the Parity of a number Efficiently in C++
- Golang Program to find the parity of a given number.
- Program to invert bits of a number Efficiently in C++
- Program to find parity in C++
- Parity Check of a Number
- C Program for efficiently print all prime factors of a given number?
- JavaScript Program to Efficiently compute sums of diagonals of a matrix
- Program to Find Minimum Jumps Required to Reach a Value with Different Parity in Python
- 8085 program to add even parity to a string of 7 bit ASCII characters.
- 8085 program to find the factorial of a number
- 8086 program to find the factorial of a number
- Haskell Program To Find The Factorial Of A Positive Number
- Java Program to Find Factorial of a number
- Swift Program to Find Factorial of a number
- Kotlin Program to Find Factorial of a number

Advertisements