Open In App

Remove an element to maximize the GCD of the given array

Given an array arr[] of length N ≥ 2. The task is to remove an element from the given array such that the GCD of the array after removing it is maximized.

Examples: 



Input: arr[] = {12, 15, 18} 
Output:
Remove 12: GCD(15, 18) = 3 
Remove 15: GCD(12, 18) = 6 
Remove 18: GCD(12, 15) = 3

Input: arr[] = {14, 17, 28, 70} 
Output: 14 



Approach:

In this approach, we iterate through each element of the array and remove it to get the remaining array. We then calculate the GCD of the remaining array and keep track of the maximum GCD found so far. Finally, we return the maximum GCD.




#include <bits/stdc++.h>
using namespace std;
 
int gcd(int a, int b) {
    if(b == 0) return a;
    return gcd(b, a%b);
}
 
int MaxGCD(int a[], int n) {
    int ans = 0;
 
    // Try removing each element and calculate GCD of the remaining array
    for(int i = 0; i < n; i++) {
        int temp[n-1];
        int k = 0;
        for(int j = 0; j < n; j++) {
            if(j != i) {
                temp[k++] = a[j];
            }
        }
        int res = temp[0];
        for(int j = 1; j < n-1; j++) {
            res = gcd(res, temp[j]);
        }
        ans = max(ans, res);
    }
 
    return ans;
}
 
int main() {
    int a[] = {14, 17, 28, 70};
    int n = sizeof(a)/sizeof(a[0]);
    cout << MaxGCD(a, n) << endl;
    return 0;
}




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        int[] a = {14, 17, 28, 70};
        int n = a.length;
 
        // Call the MaxGCD function and print the result
        System.out.println(MaxGCD(a, n));
    }
 
    // Function to calculate the greatest common divisor (GCD) of two numbers using Euclidean algorithm
    public static int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
 
    // Function to find the maximum GCD of all possible subarrays by removing one element at a time
    public static int MaxGCD(int[] a, int n) {
        int ans = 0;
 
        // Try removing each element and calculate GCD of the remaining array
        for (int i = 0; i < n; i++) {
            // Create a temporary array to hold the elements of the original array except for the one at index i
            int[] temp = new int[n - 1];
            int k = 0;
            for (int j = 0; j < n; j++) {
                // Skip the element at index i while copying elements to the temporary array
                if (j != i) {
                    temp[k++] = a[j];
                }
            }
 
            // Calculate the GCD of the elements in the temporary array
            int res = temp[0];
            for (int j = 1; j < n - 1; j++) {
                res = gcd(res, temp[j]);
            }
 
            // Update the maximum GCD found so far
            ans = Math.max(ans, res);
        }
 
        // Return the maximum GCD of all subarrays obtained by removing one element at a time
        return ans;
    }
}




def gcd(a, b):
    # Euclidean algorithm to calculate GCD
    if b == 0:
        return a
    return gcd(b, a % b)
 
def max_gcd(arr):
    n = len(arr)
    ans = 0
 
    # Try removing each element and calculate GCD of the remaining array
    for i in range(n):
        temp = arr[:i] + arr[i+1:]  # Create a modified array by removing element at index i
        res = temp[0]
        for j in range(1, n - 1):
            res = gcd(res, temp[j])
        ans = max(ans, res)
 
    return ans
 
if __name__ == "__main__":
    a = [14, 17, 28, 70]
    print(max_gcd(a))




using System;
 
namespace MaxGCD
{
    class Program
    {
        // Function to calculate the greatest common divisor (GCD)
        static int Gcd(int a, int b)
        {
            if (b == 0)
                return a;
            return Gcd(b, a % b);
        }
 
        // Function to calculate the maximum GCD after removing each element
        static int MaxGCD(int[] a, int n)
        {
            int ans = 0;
 
            // Try removing each element and calculate GCD of the remaining array
            for (int i = 0; i < n; i++)
            {
                int[] temp = new int[n - 1];
                int k = 0;
                for (int j = 0; j < n; j++)
                {
                    if (j != i)
                    {
                        temp[k++] = a[j];
                    }
                }
                int res = temp[0];
                for (int j = 1; j < n - 1; j++)
                {
                    res = Gcd(res, temp[j]);
                }
                ans = Math.Max(ans, res);
            }
 
            return ans;
        }
 
        // Main function
        static void Main(string[] args)
        {
            int[] a = { 14, 17, 28, 70 };
            int n = a.Length;
 
            // Function call
            Console.WriteLine(MaxGCD(a, n));
        }
    }
}




function gcd( a,  b) {
    if(b == 0)
        return a;
    return gcd(b, a%b);
}
 
function MaxGCD(a,  n) {
    let ans = 0;
 
    // Try removing each element and calculate GCD of the remaining array
    for(let i = 0; i < n; i++) {
        let temp=new Array(n-1);
        let k = 0;
        for(let j = 0; j < n; j++) {
            if(j != i) {
                temp[k++] = a[j];
            }
        }
        let res = temp[0];
        for(let j = 1; j < n-1; j++) {
            res = gcd(res, temp[j]);
        }
        ans = Math.max(ans, res);
    }
 
    return ans;
}
 
let a = [14, 17, 28, 70];
let n = a.length;
document.write(MaxGCD(a, n));

Output
14







Time Complexity: O(n^2 * log(max(a))), where n is the size of the array and max(a) is the maximum value in the array. This is because the function gcd has a time complexity of O(log(max(a))) and the function MaxGCD has two nested loops, each of which iterates n times.

Auxiliary Space: O(n^2) because the function MaxGCD creates a new array of size n-1 for each element of the input array, resulting in n^2 total elements in all created arrays.

Approach:  

Below is the implementation of the above approach:  




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximized gcd
// after removing a single element
// from the given array
int MaxGCD(int a[], int n)
{
 
    // Prefix and Suffix arrays
    int Prefix[n + 2];
    int Suffix[n + 2];
 
    // Single state dynamic programming relation
    // for storing gcd of first i elements
    // from the left in Prefix[i]
    Prefix[1] = a[0];
    for (int i = 2; i <= n; i += 1) {
        Prefix[i] = __gcd(Prefix[i - 1], a[i - 1]);
    }
 
    // Initializing Suffix array
    Suffix[n] = a[n - 1];
 
    // Single state dynamic programming relation
    // for storing gcd of all the elements having
    // greater than or equal to i in Suffix[i]
    for (int i = n - 1; i >= 1; i -= 1) {
        Suffix[i] = __gcd(Suffix[i + 1], a[i - 1]);
    }
 
    // If first or last element of
    // the array has to be removed
    int ans = max(Suffix[2], Prefix[n - 1]);
 
    // If any other element is replaced
    for (int i = 2; i < n; i += 1) {
        ans = max(ans, __gcd(Prefix[i - 1], Suffix[i + 1]));
    }
 
    // Return the maximized gcd
    return ans;
}
 
// Driver code
int main()
{
    int a[] = { 14, 17, 28, 70 };
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << MaxGCD(a, n);
 
    return 0;
}




// Java implementation of the above approach
class Test
{
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
     
    // Function to return the maximized gcd
    // after removing a single element
    // from the given array
    static int MaxGCD(int a[], int n)
    {
     
        // Prefix and Suffix arrays
        int Prefix[] = new int[n + 2];
        int Suffix[] = new int[n + 2] ;
     
        // Single state dynamic programming relation
        // for storing gcd of first i elements
        // from the left in Prefix[i]
        Prefix[1] = a[0];
        for (int i = 2; i <= n; i += 1)
        {
            Prefix[i] = gcd(Prefix[i - 1], a[i - 1]);
        }
     
        // Initializing Suffix array
        Suffix[n] = a[n - 1];
     
        // Single state dynamic programming relation
        // for storing gcd of all the elements having
        // greater than or equal to i in Suffix[i]
        for (int i = n - 1; i >= 1; i -= 1)
        {
            Suffix[i] = gcd(Suffix[i + 1], a[i - 1]);
        }
     
        // If first or last element of
        // the array has to be removed
        int ans = Math.max(Suffix[2], Prefix[n - 1]);
     
        // If any other element is replaced
        for (int i = 2; i < n; i += 1)
        {
            ans = Math.max(ans, gcd(Prefix[i - 1], Suffix[i + 1]));
        }
     
        // Return the maximized gcd
        return ans;
    }
         
    // Driver code
    public static void main(String[] args)
    {
 
        int a[] = { 14, 17, 28, 70 };
        int n = a.length;
     
        System.out.println(MaxGCD(a, n));
    }
}
 
// This code is contributed by AnkitRai01




# Python3 implementation of the above approach
import math as mt
 
# Function to return the maximized gcd
# after removing a single element
# from the given array
 
def MaxGCD(a, n):
 
 
    # Prefix and Suffix arrays
    Prefix=[0 for i in range(n + 2)]
    Suffix=[0 for i in range(n + 2)]
 
    # Single state dynamic programming relation
    # for storing gcd of first i elements
    # from the left in Prefix[i]
    Prefix[1] = a[0]
    for i in range(2,n+1):
        Prefix[i] = mt.gcd(Prefix[i - 1], a[i - 1])
 
    # Initializing Suffix array
    Suffix[n] = a[n - 1]
 
    # Single state dynamic programming relation
    # for storing gcd of all the elements having
    # greater than or equal to i in Suffix[i]
    for i in range(n-1,0,-1):
        Suffix[i] =mt.gcd(Suffix[i + 1], a[i - 1])
 
    # If first or last element of
    # the array has to be removed
    ans = max(Suffix[2], Prefix[n - 1])
 
    # If any other element is replaced
    for i in range(2,n):
        ans = max(ans, mt.gcd(Prefix[i - 1], Suffix[i + 1]))
 
    # Return the maximized gcd
    return ans
 
# Driver code
 
a=[14, 17, 28, 70]
n = len(a)
 
print(MaxGCD(a, n))
 
# This code is contributed by mohit kumar 29




// C# implementation of the above approach
using System;
 
class GFG
{
     
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
     
    // Function to return the maximized gcd
    // after removing a single element
    // from the given array
    static int MaxGCD(int []a, int n)
    {
     
        // Prefix and Suffix arrays
        int []Prefix = new int[n + 2];
        int []Suffix = new int[n + 2] ;
     
        // Single state dynamic programming relation
        // for storing gcd of first i elements
        // from the left in Prefix[i]
        Prefix[1] = a[0];
        for (int i = 2; i <= n; i += 1)
        {
            Prefix[i] = gcd(Prefix[i - 1], a[i - 1]);
        }
     
        // Initializing Suffix array
        Suffix[n] = a[n - 1];
     
        // Single state dynamic programming relation
        // for storing gcd of all the elements having
        // greater than or equal to i in Suffix[i]
        for (int i = n - 1; i >= 1; i -= 1)
        {
            Suffix[i] = gcd(Suffix[i + 1], a[i - 1]);
        }
     
        // If first or last element of
        // the array has to be removed
        int ans = Math.Max(Suffix[2], Prefix[n - 1]);
     
        // If any other element is replaced
        for (int i = 2; i < n; i += 1)
        {
            ans = Math.Max(ans, gcd(Prefix[i - 1], Suffix[i + 1]));
        }
     
        // Return the maximized gcd
        return ans;
    }
         
    // Driver code
    static public void Main ()
    {
         
        int []a = { 14, 17, 28, 70 };
        int n = a.Length;
     
        Console.Write(MaxGCD(a, n));
    }
}
 
// This code is contributed by ajit.




<script>
 
// Javascript implementation of the above approach
 
// Recursive function to return gcd of a and b 
function gcd(a, b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
     
// Function to return the maximized gcd
// after removing a single element
// from the given array
function MaxGCD(a, n)
{
     
    // Prefix and Suffix arrays
    let Prefix = new Array(n + 2);
    let Suffix = new Array(n + 2);
 
    // Single state dynamic programming relation
    // for storing gcd of first i elements
    // from the left in Prefix[i]
    Prefix[1] = a[0];
    for(let i = 2; i <= n; i += 1)
    {
        Prefix[i] = gcd(Prefix[i - 1], a[i - 1]);
    }
 
    // Initializing Suffix array
    Suffix[n] = a[n - 1];
 
    // Single state dynamic programming relation
    // for storing gcd of all the elements having
    // greater than or equal to i in Suffix[i]
    for(let i = n - 1; i >= 1; i -= 1)
    {
        Suffix[i] = gcd(Suffix[i + 1], a[i - 1]);
    }
 
    // If first or last element of
    // the array has to be removed
    let ans = Math.max(Suffix[2], Prefix[n - 1]);
 
    // If any other element is replaced
    for(let i = 2; i < n; i += 1)
    {
        ans = Math.max(ans, gcd(Prefix[i - 1],
                                Suffix[i + 1]));
    }
     
    // Return the maximized gcd
    return ans;
}
 
// Driver code
let a = [ 14, 17, 28, 70 ];
let n = a.length;
 
document.write(MaxGCD(a, n));
 
// This code is contributed by rishavmahato348
 
</script>

Output
14






Time Complexity: O(N * log(M)) where M is the maximum element from the array.

Auxiliary Space: O(N)
 


Article Tags :