Skip to content
Related Articles

Related Articles

Improve Article

Find all possible GCDs of every subsequences of given Array

  • Difficulty Level : Hard
  • Last Updated : 09 Aug, 2021

Given an array arr[] consisting of N positive integers, the task is to find all the possible distinct Greatest Common Divisors(GCDs) among all the non-empty subsequences of the array arr[].

Examples:

Input: arr[] = {3, 4, 8}
Output: 1 3 4 8
Explanation:
The non-empty subsequences possible are {3}, {4}, {8}, {3, 4}, {4, 8}, {3, 8}, {3, 4, 8} and their corresponding GCDs are 3, 4, 8, 1, 4, 1, 1. 
Therefore, print all the GCDs as {1, 3, 4, 8}.

Input: arr[] = {3, 8, 9, 4, 13, 45, 6}
Output: 1 2 3 4 6 8 9 13 45

Naive Approach: The simplest approach to solve the given problem is to generate all possible subsequences of the given array and store all the GCDs of the subsequence in a set. After checking for all the subsequences, print the element stores in the set as all possible GCDs that can be formed.



Time Complexity: O(log M*2N), where M is the maximum element of the array.
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized using Greedy Approach by observing the fact that the GCD of any subsequence lies over the range [1, M] where M is the maximum element of the array. Therefore, the idea is to iterate over then range [1, M] and if any element in the range is a factor of an array element then print the current element as one of the resultant GCD. Follow the steps below to solve the problem:

  • Store all the array elements in the HashSet, say s.
  • Iterate over the range [1, M] using the variable i and perform the following steps:
    • Iterate through all the multiples of i, if there exists any multiple which is present in the HashSet, then print the current element i as one of the possible GCD.

Below is an implementation of the above approach:

// C++ program for the above approach

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the different GCDs of
// the subsequence of the given array
void findGCDsSubsequence(vector<int> arr)
{
     
    // Stores all the possible GCDs
    vector<int> ans;
 
    // Stores all array element in set
    set<int> s;
    for(int i : arr)
        s.insert(i);
         
    int M = *max_element(arr.begin(), arr.end());
     
    // Iterate over the range [1, M]
    for(int i = 1; i <= M; i++)
    {
        int gcd = 0;
 
        // Check if i can be the GCD of
        // any subsequence
        for(int j = i; j < M + 1; j += i)
        {
            if (s.find(j) != s.end())
                gcd = __gcd(gcd, j);
        }
        if (gcd == i)
            ans.push_back(i);
    }
    for(int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
}
 
// Driver Code
int main()
{
    int N = 7;
    vector<int> arr = { 3, 4, 8 };
 
    // Function Call
    findGCDsSubsequence(arr);
    return 0;
}
 
// This code is contributed by parthagarwal1962000

Java




// Java program for the above approach
import java.util.*;
public class GFG {
static int gcd1(int a, int b)
{
    return b == 0 ? a : gcd1(b, a % b);
}
 
// Function to find the different GCDs of
// the subsequence of the given array
static void findGCDsSubsequence(ArrayList<Integer> arr)
{
     
    // Stores all the possible GCDs
    ArrayList<Integer> ans = new ArrayList<Integer>();
 
    // Stores all array element in set
    HashSet<Integer> s = new HashSet<Integer>();
    for(int i : arr)
        s.add(i);
         
    int M = Integer.MIN_VALUE;
    for(int i : arr)
    {
        if (i > M)
            M = i;
    }
 
    // Iterate over the range [1, M]
    for(int i = 1; i <= M; i++)
    {
        int gcd = 0;
 
        // Check if i can be the GCD of
        // any subsequence
        for(int j = i; j < M + 1; j += i)
        {
            if (s.contains(j))
                gcd = gcd1(gcd, j);
        }
        if (gcd == i)
            ans.add(i);
    }
    for(int i = 0; i < ans.size(); i++)
       System.out.print(ans.get(i) + " ");
}
 
// Driver Code
 public static void main(String args[])
{
    ArrayList<Integer> arr = new ArrayList<Integer>();
    arr.add(3);
    arr.add(4);
    arr.add(8);
 
    // Function Call
    findGCDsSubsequence(arr);
}
}
// This code is contributed by SoumikMondal

Python3




# Python3 program for the above approach
import math
 
# Function to find the different GCDs of
# the subsequence of the given array
def findGCDsSubsequence(nums):
 
        # Stores all the possible GCDs
    Ans = []
 
    # Stores all array element in set
    s = set(nums)
 
    # Find the maximum array element
    M = max(nums)
 
    # Iterate over the range [1, M]
    for i in range(1, M + 1):
       
          # Stores the GCD of subsequence
        gcd = 0
 
        # Check if i can be the GCD of
        # any subsequence
        for j in range(i, M + 1, i):
            if j in s:
                gcd = math.gcd(gcd, j)
 
        # Store the value i in Ans[]
        # if it can be the GCD
        if gcd == i:
            Ans += [i]
 
    # Print all possible GCDs stored
    print(*Ans)
 
 
# Driver Code
N = 7
arr = [3, 4, 8]
 
# Function Call
findGCDsSubsequence(arr)

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
static int gcd1(int a, int b)
{
    return b == 0 ? a : gcd1(b, a % b);
}
 
// Function to find the different GCDs of
// the subsequence of the given array
static void findGCDsSubsequence(List<int> arr)
{
     
    // Stores all the possible GCDs
    List<int> ans = new List<int>();
 
    // Stores all array element in set
    HashSet<int> s = new HashSet<int>();
    foreach(int i in arr)
        s.Add(i);
         
    int M = Int32.MinValue;
    foreach(int i in arr)
    {
        if (i > M)
            M = i;
    }
 
    // Iterate over the range [1, M]
    for(int i = 1; i <= M; i++)
    {
        int gcd = 0;
 
        // Check if i can be the GCD of
        // any subsequence
        for(int j = i; j < M + 1; j += i)
        {
            if (s.Contains(j))
                gcd = gcd1(gcd, j);
        }
        if (gcd == i)
            ans.Add(i);
    }
    for(int i = 0; i < ans.Count; i++)
        Console.Write(ans[i] + " ");
}
 
// Driver Code
public static void Main()
{
    List<int> arr = new List<int>(){ 3, 4, 8 };
 
    // Function Call
    findGCDsSubsequence(arr);
}
}
 
// This code is contributed by SURENDRA_GANGWAR

Javascript




<script>
 
// JavaScript program for the above approach
 
function __gcd(a, b) {
    if (b == 0)
    return a;
    return __gcd(b, a % b);
 }
  
 
// Function to find the different GCDs of
// the subsequence of the given array
function findGCDsSubsequence(arr) {
 
    // Stores all the possible GCDs
    let ans = [];
 
    // Stores all array element in set
    let s = new Set();
    for (let i of arr)
        s.add(i);
 
    let M = [...arr].sort((a, b) => b - a)[0]
 
    // Iterate over the range [1, M]
    for (let i = 1; i <= M; i++) {
        let gcd = 0;
 
        // Check if i can be the GCD of
        // any subsequence
        for (let j = i; j < M + 1; j += i) {
            if (s.has(j))
                gcd = __gcd(gcd, j);
        }
        if (gcd == i)
            ans.push(i);
    }
    for (let i = 0; i < ans.length; i++)
        document.write(ans[i] + " ");
}
 
// Driver Code
 
let N = 7;
let arr = [3, 4, 8];
 
// Function Call
findGCDsSubsequence(arr);
 
// This code is contributed by gfgking
 
</script>
Output
1 3 4 8

Time Complexity: O(M*log M), where M is the maximum element of the array.
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :