Count number of subsets of a set with GCD equal to a given number
Last Updated :
23 Jul, 2025
Given a set of positive integer elements, find the count of subsets with GCDs equal to given numbers.
Examples:
Input: arr[] = {2, 3, 4}, gcd[] = {2, 3}
Output: Number of subsets with gcd 2 is 2
Number of subsets with gcd 3 is 1
The two subsets with GCD equal to 2 are {2} and {2, 4}.
The one subset with GCD equal to 3 ss {3}.
Input: arr[] = {6, 3, 9, 2}, gcd = {3, 2}
Output: Number of subsets with gcd 3 is 5
Number of subsets with gcd 2 is 2
The five subsets with GCD equal to 3 are {3}, {6, 3},
{3, 9}, {6, 9) and {6, 3, 9}.
The two subsets with GCD equal to 2 are {2} and {2, 6}
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to generate all subsets of given set and find GCD of every subset.
Below is an Efficient Solution for small numbers, i,e, the maximum of all numbers is not very high.
1) Find the maximum number of given numbers. Let the
maximum be arrMax.
2) Count occurrences of all numbers using a hash. Let
this hash be 'freq'
3) The maximum possible GCD can be arrMax. Run a loop
for i = arrMax to 1
a) Count number of subsets for current GCD.
4) Now we have counts for all possible GCDs, return
count for given gcds.
How does step 3.a work?
How to get the number of subsets for a given GCD 'i' where i lies in the range from 1 to arrMax. The idea is to count all multiples of i using 'freq' built-in step 2. Let there be 'add' multiples of i. The number of all possible subsets with 'add' numbers would be "pow(2, add) - 1", excluding the empty set. For example, if given array is {2, 3, 6} and i = 3, there are 2 multiples of 3 (3 and 6). So there will be 3 subsets {3}, {3, 6} and {6} which have a multiple of i as GCD. These subsets also include {6} which doesn't have 3 as GCD, but a multiple of 3. So we need to subtract such subsets. We store subset counts for every GCD in another hash map 'subset'. Let 'sub' be the number of subsets that have multiple of 'i' as GCD. The value of 'sub' for any multiple of 'i' can directly be obtained from subset[] as we are evaluating counts from arrMax to 1.
Below is the implementation of the above idea.
C++
// C++ program to count number of subsets with given GCDs
#include<bits/stdc++.h>
using namespace std;
// n is size of arr[] and m is sizeof gcd[]
void ccountSubsets(int arr[], int n, int gcd[], int m)
{
// Map to store frequency of array elements
unordered_map<int, int> freq;
// Map to store number of subsets with given gcd
unordered_map<int, int> subsets;
// Initialize maximum element. Assumption: all array
// elements are positive.
int arrMax = 0;
// Find maximum element in array and fill frequency
// map.
for (int i=0; i<n; i++)
{
arrMax = max(arrMax, arr[i]);
freq[arr[i]]++;
}
// Run a loop from max element to 1 to find subsets
// with all gcds
for (int i=arrMax; i>=1; i--)
{
int sub = 0;
int add = freq[i];
// Run a loop for all multiples of i
for (int j = 2; j*i <= arrMax; j++)
{
// Sum the frequencies of every element which
// is a multiple of i
add += freq[j*i];
// Excluding those subsets which have gcd > i but
// not i i.e. which have gcd as multiple of i in
// the subset for ex: {2,3,4} considering i = 2 and
// subset we need to exclude are those having gcd as 4
sub += subsets[j*i];
}
// Number of subsets with GCD equal to 'i' is pow(2, add)
// - 1 - sub
subsets[i] = (1<<add) - 1 - sub;
}
for (int i=0; i<m; i++)
cout << "Number of subsets with gcd " << gcd[i] << " is "
<< subsets[gcd[i]] << endl;
}
// Driver program
int main()
{
int gcd[] = {2, 3};
int arr[] = {9, 6, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int m = sizeof(gcd)/sizeof(gcd[0]);
ccountSubsets(arr, n, gcd, m);
return 0;
}
Java
// Java program to count
// number of subsets with
// given GCDs
import java.util.*;
class GFG{
// n is size of arr[] and
// m is sizeof gcd[]
static void ccountSubsets(int arr[], int n,
int gcd[], int m)
{
// Map to store frequency
// of array elements
HashMap<Integer,
Integer> freq =
new HashMap<Integer,
Integer>();
// Map to store number of
// subsets with given gcd
HashMap<Integer,
Integer> subsets =
new HashMap<Integer,
Integer>();
// Initialize maximum element.
// Assumption: all array
// elements are positive.
int arrMax = 0;
// Find maximum element in
// array and fill frequency
// map.
for (int i = 0; i < n; i++)
{
arrMax = Math.max(arrMax,
arr[i]);
if(freq.containsKey(arr[i]))
{
freq.put(arr[i],
freq.get(arr[i]) + 1);
}
else
{
freq.put(arr[i], 1);
}
}
// Run a loop from max element
// to 1 to find subsets
// with all gcds
for (int i = arrMax; i >= 1; i--)
{
int sub = 0;
int add = 0;
if(freq.containsKey(i))
add = freq.get(i);
// Run a loop for all multiples
// of i
for (int j = 2; j * i <= arrMax; j++)
{
// Sum the frequencies of
// every element which
// is a multiple of i
if(freq.containsKey(i * j))
add += freq.get(j * i);
// Excluding those subsets
// which have gcd > i but
// not i i.e. which have
// gcd as multiple of i in
// the subset for ex: {2,3,4}
// considering i = 2 and
// subset we need to exclude
// are those having gcd as 4
sub += subsets.get(j * i);
}
// Number of subsets with GCD
// equal to 'i' is Math.pow(2, add)
// - 1 - sub
subsets.put(i, (1 << add) -
1 - sub);
}
for (int i = 0; i < m; i++)
System.out.print("Number of subsets with gcd " +
gcd[i] + " is " +
subsets.get(gcd[i]) + "\n");
}
// Driver program
public static void main(String[] args)
{
int gcd[] = {2, 3};
int arr[] = {9, 6, 2};
int n = arr.length;
int m = gcd.length;
ccountSubsets(arr, n, gcd, m);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program to count number of
# subsets with given GCDs
# n is size of arr[] and m is sizeof gcd[]
def countSubsets(arr, n, gcd, m):
# Map to store frequency of array elements
freq = dict()
# Map to store number of subsets
# with given gcd
subsets = dict()
# Initialize maximum element.
# Assumption: all array elements
# are positive.
arrMax = 0
# Find maximum element in array and
# fill frequency map.
for i in range(n):
arrMax = max(arrMax, arr[i])
if arr[i] not in freq:
freq[arr[i]] = 1
else:
freq[arr[i]] += 1
# Run a loop from max element to 1
# to find subsets with all gcds
for i in range(arrMax, 0, -1):
sub = 0
add = 0
if i in freq:
add = freq[i]
j = 2
# Run a loop for all multiples of i
while j * i <= arrMax:
# Sum the frequencies of every element
# which is a multiple of i
if j * i in freq:
add += freq[j * i]
# Excluding those subsets which have
# gcd > i but not i i.e. which have gcd
# as multiple of i in the subset.
# for ex: {2,3,4} considering i = 2 and
# subset we need to exclude are those
# having gcd as 4
sub += subsets[j * i]
j += 1
# Number of subsets with GCD equal
# to 'i' is pow(2, add) - 1 - sub
subsets[i] = (1 << add) - 1 - sub
for i in range(m):
print("Number of subsets with gcd %d is %d" %
(gcd[i], subsets[gcd[i]]))
# Driver Code
if __name__ == "__main__":
gcd = [2, 3]
arr = [9, 6, 2]
n = len(arr)
m = len(gcd)
countSubsets(arr, n, gcd, m)
# This code is contributed by
# sanjeev2552
C#
// C# program to count
// number of subsets with
// given GCDs
using System;
using System.Collections.Generic;
class GFG{
// n is size of []arr and
// m is sizeof gcd[]
static void ccountSubsets(int []arr, int n,
int []gcd, int m)
{
// Map to store frequency
// of array elements
Dictionary<int,
int> freq =
new Dictionary<int,
int>();
// Map to store number of
// subsets with given gcd
Dictionary<int,
int> subsets =
new Dictionary<int,
int>();
// Initialize maximum element.
// Assumption: all array
// elements are positive.
int arrMax = 0;
// Find maximum element in
// array and fill frequency
// map.
for (int i = 0; i < n; i++)
{
arrMax = Math.Max(arrMax,
arr[i]);
if(freq.ContainsKey(arr[i]))
{
freq.Add(arr[i],
freq[arr[i]] + 1);
}
else
{
freq.Add(arr[i], 1);
}
}
// Run a loop from max element
// to 1 to find subsets
// with all gcds
for (int i = arrMax; i >= 1; i--)
{
int sub = 0;
int add = 0;
if(freq.ContainsKey(i))
add = freq[i];
// Run a loop for all
// multiples of i
for (int j = 2;
j * i <= arrMax; j++)
{
// Sum the frequencies of
// every element which
// is a multiple of i
if(freq.ContainsKey(i * j))
add += freq[j * i];
// Excluding those subsets
// which have gcd > i but
// not i i.e. which have
// gcd as multiple of i in
// the subset for ex: {2,3,4}
// considering i = 2 and
// subset we need to exclude
// are those having gcd as 4
sub += subsets[j * i];
}
// Number of subsets with GCD
// equal to 'i' is Math.Pow(2, add)
// - 1 - sub
subsets.Add(i, (1 << add) -
1 - sub);
}
for (int i = 0; i < m; i++)
Console.Write("Number of subsets with gcd " +
gcd[i] + " is " +
subsets[gcd[i]] + "\n");
}
// Driver code
public static void Main(String[] args)
{
int []gcd = {2, 3};
int []arr = {9, 6, 2};
int n = arr.Length;
int m = gcd.Length;
ccountSubsets(arr, n, gcd, m);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program to count number of
// subsets with given GCDs
// n is size of arr[] and m is sizeof gcd[]
function countSubsets(arr, n, gcd, m){
// Map to store frequency of array elements
let freq = new Map
// Map to store number of subsets
// with given gcd
let subsets = new Map
// Initialize maximum element.
// Assumption: all array elements
// are positive.
let arrMax = 0
// Find maximum element in array and
// fill frequency map.
for(let i = 0; i < n; i++)
{
arrMax = Math.max(arrMax, arr[i])
if(freq.has(arr[i]) == false)
freq.set(arr[i], 1)
else
freq.set(arr[i], freq.get(arr[i])+1)
}
// Run a loop from max element to 1
// to find subsets with all gcds
for(let i = arrMax; i > 0; i--)
{
let sub = 0
let add = 0
if(freq.has(i))
add = freq.get(i)
let j = 2
// Run a loop for all multiples of i
while(j * i <= arrMax){
// Sum the frequencies of every element
// which is a multiple of i
if(freq.has(j * i))
add += freq.get(j * i)
// Excluding those subsets which have
// gcd > i but not i i.e. which have gcd
// as multiple of i in the subset.
// for ex: {2,3,4} considering i = 2 and
// subset we need to exclude are those
// having gcd as 4
sub += subsets.get(j * i)
j += 1
}
// Number of subsets with GCD equal
// to 'i' is pow(2, add) - 1 - sub
subsets.set(i , (1 << add) - 1 - sub)
}
for(let i = 0; i < m; i++)
{
document.write( `Number of subsets with gcd ${gcd[i]} is ${subsets.get(gcd[i])}`,"</br>")
}
}
// Driver Code
let gcd = [2, 3]
let arr = [9, 6, 2]
let n = arr.length
let m = gcd.length
countSubsets(arr, n, gcd, m)
// This code is contributed by shinjanpatra
</script>
Output:
Number of subsets with gcd 2 is 2
Number of subsets with gcd 3 is 1
Time Complexity: O(n * log(max(arr)) * sqrt(max(arr))), where n is the size of the input array and max(arr) represents the maximum element in the array.
Auxiliary Space: O(max(arr)), as it uses two unordered maps to store frequency of array elements and the number of subsets with a given gcd. The space required by the maps depends on the maximum element in the array.
Exercise: Extend the above solution so that all calculations are done under modulo 1000000007 to avoid overflows.
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