Smallest subsequence having GCD equal to GCD of given array

Given an array arr[] of size N, the task is to find the smallest subsequence of the given array whose GCD of the subsequence is equal to the GCD of the given array. If more than one such subsequence exists, then print anyone of them.

Examples:

Input: arr[] = {4, 6, 12}
Output: 4 6
Explanation: Smallest subsequence having gcd equal to gcd of the given array(= 2) is {4, 6}. Therefore, the required output is {4, 6}

Input: arr[] = {6, 12, 18, 24}
Output: 6

 

Naive Approach: The simplest approach to solve this problem is to generate all possible subsequences of the given array and calculate GCD of each subsequence. Print the smallest subsequence having gcd equal to gcd of the given array. 



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

Efficient Approach: To optimize the above approach the idea is based on the following observations:

Length of the smallest subsequence having gcd equal to gcd of the given array must be either 1 or 2.

Consider, gcd of the given array is Y.

If arr[idx] = Y, then length of the smallest subsequence must be 1 for some value of idx.

Otherwise, length of the smallest subsequence must be 2.

Proof using Contradiction method:
If gcd of all possible pairs of the given array is greater than Y, then gcd of the given array must be greater than Y, which is not possible.
Therefore, at least one pair exists in the given array whose gcd is equal to Y.

Follow the steps below to solve the problem:

  • Initialize a variable gcdArr to store GCD of the array.
  • Traverse the given array and check if any array element is equal to gcdArr or not. If found to be true, print that element.
  • Otherwise, print a pair from the given array whose gcd is equal to gcdArr.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print
// the smallest subsequence
// that satisfies the condition
void printSmallSub(int arr[], int N)
{
    // Stores gcd of the array.
    int gcdArr = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Update gcdArr
        gcdArr = __gcd(gcdArr, arr[i]);
    }
 
    // Traverse the given array.
    for (int i = 0; i < N; i++) {
 
        // If current element
        // equal to gcd of array.
        if (arr[i] == gcdArr) {
            cout << arr[i] << " ";
            return;
        }
    }
 
    // Generate all possible pairs.
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N;
             j++) {
 
            // If gcd of current pair
            // equal to gcdArr
            if (__gcd(arr[i], arr[j])
                == gcdArr) {
 
                // Print current pair
                // of the array
                cout << arr[i] << " " << arr[j];
                return;
            }
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 6, 12 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    printSmallSub(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to calculate gcd
// of two numbers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
 
// Function to print
// the smallest subsequence
// that satisfies the condition
static void printSmallSub(int[] arr, int N)
{
     
    // Stores gcd of the array.
    int gcdArr = 0;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // Update gcdArr
        gcdArr = gcd(gcdArr, arr[i]);
    }
 
    // Traverse the given array.
    for(int i = 0; i < N; i++)
    {
         
        // If current element
        // equal to gcd of array.
        if (arr[i] == gcdArr)
        {
            System.out.print(arr[i] + " ");
            return;
        }
    }
 
    // Generate all possible pairs.
    for(int i = 0; i < N; i++)
    {
        for(int j = i + 1; j < N; j++)
        {
             
            // If gcd of current pair
            // equal to gcdArr
            if (gcd(arr[i], arr[j]) == gcdArr)
            {
                 
                // Print current pair
                // of the array
                System.out.print(arr[i] + " " +
                                 arr[j]);
                return;
            }
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 6, 12 };
    int N = arr.length;
 
    printSmallSub(arr, N);
}
}
 
// This code is contributed by akhilsaini

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
import math
 
# Function to print the
# smallest subsequence
# that satisfies the condition
def printSmallSub(arr, N):
     
    # Stores gcd of the array.
    gcdArr = 0
 
    # Traverse the given array
    for i in range(0, N):
         
        # Update gcdArr
        gcdArr = math.gcd(gcdArr, arr[i])
 
    # Traverse the given array.
    for i in range(0, N):
         
        # If current element
        # equal to gcd of array.
        if (arr[i] == gcdArr):
            print(arr[i], end = " ")
            return
 
        # Generate all possible pairs.
        for i in range(0, N):
            for j in range(i + 1, N):
                 
                # If gcd of current pair
                # equal to gcdArr
                if (math.gcd(arr[i],
                             arr[j]) == gcdArr):
 
                    # Print current pair
                    # of the array
                    print(arr[i], end = " ")
                    print(arr[j], end = " ")
                    return
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 4, 6, 12 ]
    N = len(arr)
     
    printSmallSub(arr, N)
 
# This code is contributed by akhilsaini

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate gcd
// of two numbers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
 
// Function to print the
// smallest subsequence
// that satisfies the condition
static void printSmallSub(int[] arr, int N)
{
     
    // Stores gcd of the array.
    int gcdArr = 0;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // Update gcdArr
        gcdArr = gcd(gcdArr, arr[i]);
    }
 
    // Traverse the given array.
    for(int i = 0; i < N; i++)
    {
         
        // If current element
        // equal to gcd of array.
        if (arr[i] == gcdArr)
        {
            Console.Write(arr[i] + " ");
            return;
        }
    }
 
    // Generate all possible pairs.
    for(int i = 0; i < N; i++)
    {
        for(int j = i + 1; j < N; j++)
        {
             
            // If gcd of current pair
            // equal to gcdArr
            if (gcd(arr[i], arr[j]) == gcdArr)
            {
                 
                // Print current pair
                // of the array
                Console.Write(arr[i] + " " +
                              arr[j]);
                return;
            }
        }
    }
}
 
// Driver Code
public static void Main()
{
 
    int[] arr = { 4, 6, 12 };
    int N = arr.Length;
 
    printSmallSub(arr, N);
}
}
 
// This code is contributed by akhilsaini

chevron_right


Output: 

4 6




 

Time Complexity: (N2 * log X), where X is the maximum element of the given array.
Auxiliary Space: O(1)

 

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.




My Personal Notes arrow_drop_up

Active and well versed member of Competitive Programming

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : akhilsaini