VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-find-parity/

⇱ Program to find parity - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find parity

Last Updated : 23 Jul, 2025

Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has "odd parity" if it contains an odd number of 1-bits and is "even parity" if it contains an even number of 1-bits. 
The main idea of the below solution is - Loop while n is not 0 and in loop unset one of the set bits and invert parity.

Algorithm: getParity(n)
1. Initialize parity = 0
2. Loop while n != 0 
 a. Invert parity 
 parity = !parity
 b. Unset rightmost set bit
 n = n & (n-1)
3. return parity

Example:
 Initialize: n = 13 (1101) parity = 0

n = 13 & 12 = 12 (1100) parity = 1
n = 12 & 11 = 8 (1000) parity = 0
n = 8 & 7 = 0 (0000) parity = 1


Program: 


Output
Parity of no 7 = odd

Above solution can be optimized by using lookup table. Please refer to Bit Twiddle Hacks[1st reference] for details.
Time Complexity: The time taken by above algorithm is proportional to the number of bits set. Worst case complexity is O(Log n).
Auxiliary Space: O(1)

Another approach: (Using built-in-function)


Output
Parity of no 7 = odd

Time Complexity: O(1)

Auxiliary Space: O(1)

Another Approach: Mapping numbers with the bit 

We can use a map or an array of the number of bits to form a nibble (a nibble consists of 4 bits, so a 16 - length array would be required). Then, we can get the nibbles of a given number.

This approach can be summarized into the following steps:

1. Build the 16 length array of the number of bits to form a nibble - { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }

2. Recursively count the set of the bits by taking the last nibble (4 bits) from the array using the formula num & 0xf and then getting each successive nibble by discarding the last 4 bits using >> operator.

3. Check the parity: if the number of set bits is even, ie numOfSetBits % 2 == 0, then the number is of even parity. Else, it is of odd parity.


Output
Parity of no 7 = odd

Time Complexity: O(1)

Auxiliary Space: O(1)

Uses: Parity is used in error detection and cryptography. 

References: 
http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive - last checked on 30 May 2009.

Comment
Article Tags: