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:
C++
// C++ program to find parity
// of an integer
# include<bits/stdc++.h>
# define bool int
using namespace std;
// Function to get parity of number n. It returns 1
// if n has odd parity, and returns 0 if n has even
// parity
bool getParity(unsigned int n)
{
bool parity = 0;
while (n)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}
/* Driver program to test getParity() */
int main()
{
unsigned int n = 7;
cout<<"Parity of no "<<n<<" = "<<(getParity(n)? "odd": "even");
getchar();
return 0;
}
C
// C program to find parity
// of an integer
# include <stdio.h>
# define bool int
/* Function to get parity of number n. It returns 1
if n has odd parity, and returns 0 if n has even
parity */
bool getParity(unsigned int n)
{
bool parity = 0;
while (n)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}
/* Driver program to test getParity() */
int main()
{
unsigned int n = 7;
printf("Parity of no %d = %s", n,
(getParity(n)? "odd": "even"));
getchar();
return 0;
}
Java
// Java program to find parity
// of an integer
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
class GFG
{
/* Function to get parity of number n.
It returns 1 if n has odd parity, and
returns 0 if n has even parity */
static boolean getParity(int n)
{
boolean parity = false;
while(n != 0)
{
parity = !parity;
n = n & (n-1);
}
return parity;
}
/* Driver program to test getParity() */
public static void main (String[] args)
{
int n = 7;
System.out.println("Parity of no " + n + " = " +
(getParity(n)? "odd": "even"));
}
}
/* This code is contributed by Amit khandelwal*/
Python3
# Python3 code to get parity.
# Function to get parity of number n.
# It returns 1 if n has odd parity,
# and returns 0 if n has even parity
def getParity( n ):
parity = 0
while n:
parity = ~parity
n = n & (n - 1)
return parity
# Driver program to test getParity()
n = 7
print ("Parity of no ", n," = ",
( "odd" if getParity(n) else "even"))
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to find parity of an integer
using System;
class GFG {
/* Function to get parity of number n.
It returns 1 if n has odd parity, and
returns 0 if n has even parity */
static bool getParity(int n)
{
bool parity = false;
while(n != 0)
{
parity = !parity;
n = n & (n-1);
}
return parity;
}
// Driver code
public static void Main ()
{
int n = 7;
Console.Write("Parity of no " + n
+ " = " + (getParity(n)?
"odd": "even"));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find the parity
// of an unsigned integer
// Function to get parity of
// number n. It returns 1
// if n has odd parity, and
// returns 0 if n has even
// parity
function getParity( $n)
{
$parity = 0;
while ($n)
{
$parity = !$parity;
$n = $n & ($n - 1);
}
return $parity;
}
// Driver Code
$n = 7;
echo "Parity of no ",$n ," = " ,
getParity($n)? "odd": "even";
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript program to find parity
// of an integer
// Function to get parity of number n.
// It returns 1 if n has odd parity, and
// returns 0 if n has even parity
function getParity(n)
{
var parity = false;
while(n != 0)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}
// Driver code
var n = 7;
document.write("Parity of no " + n + " = " +
(getParity(n) ? "odd": "even"));
// This code is contributed by Kirti
</script>
OutputParity 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)
C++
// C++ program to find parity
// of an integer
# include<bits/stdc++.h>
# define bool int
using namespace std;
// Function to get parity of number n. It returns 1
// if n has odd parity, and returns 0 if n has even
// parity
bool getParity(unsigned int n)
{
return __builtin_parity(n);
}
// Driver code
int main()
{
unsigned int n = 7;
cout<<"Parity of no "<<n<<" = "<<(getParity(n)? "odd": "even");
getchar();
return 0;
}
// This code is contributed by Kasina Dheeraj
Java
// Java program to implement approach
import java.util.*;
class Main {
// Function to get parity of number n. It returns 1
// if n has odd parity, and returns 0 if n has even
// parity
public static boolean getParity(int n) {
return Integer.bitCount(n) % 2 == 1;
}
// Driver code
public static void main(String[] args) {
int n = 7;
System.out.println("Parity of no " + n + " = " + (getParity(n) ? "odd" : "even"));
}
}
// This code is contributed by phasing17
Python3
# Python program to find parity
# of an integer
# Function to get parity of number n. It returns 1
# if n has odd parity, and returns 0 if n has even
# parity
def getParity(n):
return (bin(n).count("1"))%2
# Driver code
n=7
print("Parity of no {0} = ".format(n),end="")
print("odd" if getParity(n) else "even")
# This code is contributed by Pushpesh Raj
C#
// C# code to implement the approach
using System;
using System.Linq;
class GFG
{
// Function to get parity of number n. It returns 1
// if n has odd parity, and returns 0 if n has even
// parity
public static bool GetParity(int n)
{
return Convert.ToInt32(Convert.ToString(n, 2).Count(x => x == '1')) % 2 == 1;
}
// Driver code
public static void Main()
{
int n = 7;
Console.WriteLine("Parity of no " + n + " = " + (GetParity(n) ? "odd" : "even"));
}
}
// This code is contributed by phasing17
JavaScript
// JS program to implement the above approach
// Function to get parity of number n. It returns 1
// if n has odd parity, and returns 0 if n has even parity
const getParity = (n) => {
return (n.toString(2).split("1").length - 1) % 2;
};
// Driver code
const n = 7;
console.log(`Parity of no ${n} =`, getParity(n) ? "odd" : "even");
// This code is implemented by Phasing17
OutputParity 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.
C++
// C++ program to get the parity of the
// binary representation of a number
#include <bits/stdc++.h>
using namespace std;
int nibble_to_bits[16]
= { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
// Function to recursively get the nibble
// of a given number and map them in the array
unsigned int countSetBits(unsigned int num)
{
int nibble = 0;
if (0 == num)
return nibble_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return nibble_to_bits[nibble] + countSetBits(num >> 4);
}
// Function to get the parity of a number
bool getParity(int num) { return countSetBits(num) % 2; }
// Driver code
int main()
{
unsigned int n = 7;
// Function call
cout << "Parity of no " << n << " = "
<< (getParity(n) ? "odd" : "even");
return 0;
}
// This code is contributed by phasing17
Java
// Java program to get the parity of the
// binary representation of a number
import java.util.*;
class GFG{
static int[] nibble_to_bits = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
};
// Function to recursively get the nibble
// of a given number and map them in the array
static int countSetBits(int num)
{
int nibble = 0;
if (0 == num)
return nibble_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return nibble_to_bits[nibble]
+ countSetBits(num >> 4);
}
// Function to get the parity of a number
static boolean getParity(int num)
{
return countSetBits(num) % 2 == 1;
}
// Driver code
public static void main(String[] args)
{
int n = 7;
// Function call
System.out.print(
"Parity of no " + n + " = "
+ (getParity(n) ? "odd" : "even"));
}
}
// This code is contributed by sanjoy_62.
Python3
# Python3 program to get the parity of the
# binary representation of a number
nibble_to_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
# Function to recursively get the nibble
# of a given number and map them in the array
def countSetBits(num):
nibble = 0
if (0 == num):
return nibble_to_bits[0]
# Find last nibble
nibble = num & 0xf
# Use pre-stored values to find count
# in last nibble plus recursively add
# remaining nibbles.
return nibble_to_bits[nibble] + countSetBits(num >> 4)
# Function to get the parity of a number
def getParity(num):
return countSetBits(num) % 2
# Driver code
n = 7
# Function call
print("Parity of no", n, " = ", ["even", "odd"][getParity(n)])
# This code is contributed by phasing17
C#
// C# program to get the parity of the
// binary representation of a number
using System;
class GFG {
static int[] nibble_to_bits = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
};
// Function to recursively get the nibble
// of a given number and map them in the array
static int countSetBits(int num)
{
int nibble = 0;
if (0 == num)
return nibble_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return nibble_to_bits[nibble]
+ countSetBits(num >> 4);
}
// Function to get the parity of a number
static bool getParity(int num)
{
return countSetBits(num) % 2 == 1;
}
// Driver code
public static void Main(string[] args)
{
int n = 7;
// Function call
Console.WriteLine(
"Parity of no " + n + " = "
+ (getParity(n) ? "odd" : "even"));
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript program to get the parity of the
// binary representation of a number
let nibble_to_bits
= [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ];
// Function to recursively get the nibble
// of a given number and map them in the array
function countSetBits(num)
{
let nibble = 0;
if (0 == num)
return nibble_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return nibble_to_bits[nibble] + countSetBits(num >> 4);
}
// Function to get the parity of a number
function getParity(num) { return countSetBits(num) % 2; }
// Driver code
let n = 7;
// Function call
console.log("Parity of no " + n + " = "+ (getParity(n) ? "odd" : "even"));
// This code is contributed by phasing17
OutputParity of no 7 = odd
Time Complexity: O(1)
Auxiliary Space: O(1)
Uses: Parity is used in error detection and cryptography.
Compute the parity of a number using XOR and table look-up
References:
http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive - last checked on 30 May 2009.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem