Open In App

Minimize Array sum by replacing an element with GCD

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of the length N. The task is to find the minimum sum of the array (i.e. A1 + A2 + … + AN) by performing the following operation on the given array any number (0 or more) of times:

  • Take any two indices i and j such that 0 ? i, j < N and swap either Ai or Aj  with gcd(Ai, Aj).

Examples:

Input: A[] = {3, 3, 9} 
Output: 9
Explanation: Choose i = 0 and j = 2 and replace A?3 with gcd(3, 9) = 3.
Now array A[]={3, 3, 3} and sum = 9 which is minimum possible sum of given array.

Input: A[] = {7, 14}
Output: 14

Approach 1:

The idea is to find the GCD of each pair of elements in the array and replace the larger element with the GCD. This will reduce the sum of the array as much as possible.

Algorithm:

  • Calculate the GCD of each pair of elements in the array.
  • Replace the larger element with the GCD.
  • Repeat the above steps until all the elements in the array are equal.
  • Calculate the sum of the array.
       

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate GCD of two numbers
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to calculate the minimum sum of the array
int minSum(int arr[], int n)
{
    // Iterate over all pairs of elements in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            // Calculate GCD of arr[i] and arr[j]
            int g = gcd(arr[i], arr[j]);
 
            // Replace arr[i] and arr[j] with GCD
            arr[i] = g;
            arr[j] = g;
        }
    }
 
    // Calculate sum of the array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 3, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << minSum(arr, n);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Function to find gcd of two numbers
    public static int gcd(int a, int b)
    {
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
 // Function to find the minimum
// sum of array
    public static int minSum(int arr[], int n)
{
    // Iterate over all pairs of elements in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            // Calculate GCD of arr[i] and arr[j]
            int g = gcd(arr[i], arr[j]);
 
            // Replace arr[i] and arr[j] with GCD
            arr[i] = g;
            arr[j] = g;
        }
    }
 
    // Calculate sum of the array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    return sum;
}
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 3, 3, 9 };
        int n = arr.length;
 
        // Function call
        System.out.println(minSum(arr, n));
    }
}


Python3




def gcd(a: int, b: int) -> int:
    if a == 0:
        return b
    return gcd(b % a, a)
 
# Function to calculate the minimum sum of the array
def min_sum(arr, n):
   
    # Iterate over all pairs of elements in the array
    for i in range(n):
        for j in range(i + 1, n):
           
            # Calculate GCD of arr[i] and arr[j]
            g = gcd(arr[i], arr[j])
 
            # Replace arr[i] and arr[j] with GCD
            arr[i] = g
            arr[j] = g
 
    # Calculate sum of the array
    s = 0
    for i in range(n):
        s += arr[i]
 
    return s
 
# Driver code
if __name__ == "__main__":
    arr = [3, 3, 9]
    n = len(arr)
 
    print(min_sum(arr, n))
 
    # This code is contributed by divya_p123.


C#




using System;
 
public class Program {
    // Function to find gcd of two numbers
    public static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
 
    // Function to find the minimum sum of array
    public static int minSum(int[] arr, int n)
    {
        // Iterate over all pairs of elements in the array
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // Calculate GCD of arr[i] and arr[j]
                int g = gcd(arr[i], arr[j]);
 
                // Replace arr[i] and arr[j] with GCD
                arr[i] = g;
                arr[j] = g;
            }
        }
 
        // Calculate sum of the array
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
 
        return sum;
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 3, 3, 9 };
        int n = arr.Length;
 
        // Function call
        Console.WriteLine(minSum(arr, n));
    }
}


Javascript




<script>
// JavaScript code to implement the approach
 
 
    // Function to find gcd of two numbers
    function gcd(a,  b)
    {
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
 // Function to find the minimum
// sum of array
   function minSum( arr,n)
{
    // Iterate over all pairs of elements in the array
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            // Calculate GCD of arr[i] and arr[j]
           let g = gcd(arr[i], arr[j]);
 
            // Replace arr[i] and arr[j] with GCD
            arr[i] = g;
            arr[j] = g;
        }
    }
 
    // Calculate sum of the array
    let sum = 0;
    for (let i = 0; i < n; i++)
        sum += arr[i];
 
    return sum;
}
 
    // Driver code
    
        let arr = [3, 3, 9];
        let n = arr.length;
 
        // Function call
        console.log(minSum(arr, n));
    </script>


Output

9

Time Complexity: O(N2)
Auxiliary Space: O(1)

Approach 2: To solve the problem follow the below idea:

Let G = gcd(A1, A2, . . ., AN). The answer is simply N*G. because every element can be converted to be the same as G.

Follow the below steps to solve the problem:

  • Calculate the GCD of all the array elements.
  • Multiply the result by N to get the minimum sum of the array.

Below is the implementation of the above approach.  

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find gcd of two numbers
int gcd(int p, int q) { return q == 0 ? p : gcd(q, p % q); }
 
// Function to find the minimum
// sum of array
int minSum(int A[], int N)
{
 
  int min = INT_MAX;
  for (int i = 0; i < N - 1; i++) {
    int b = gcd(A[i], A[i + 1]);
    if (b < min)
      min = b;
  }
  return min * N;
}
 
// Driver Code
int main()
{
  int A[] = { 3, 3, 9 };
  int N = sizeof(A) / sizeof(A[0]);;
 
  // Function call
  cout << minSum(A, N) << endl;
 
  return 0;
}
 
// This code is contributed by aarohirai2616.


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Function to find gcd of two numbers
    public static int gcd(int p, int q)
    {
        if (q == 0) {
            return p;
        }
        return gcd(q, p % q);
    }
 
    // Function to find the minimum
    // sum of array
    public static int minSum(int A[], int N)
    {
       int min = Integer.MAX_VALUE;
        for (int i = 0; i < N - 1; i++) {
            int b = gcd(A[i], A[i + 1]);
            if (b < min)
                min = b;
        }
        return min * N;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = { 3, 3, 9 };
        int N = A.length;
 
        // Function call
        System.out.println(minSum(A, N));
    }
}


Python3




# Python code for the above approach
import sys
 
# Function to find gcd of two numbers
def gcd(a,b):
      
    # Everything divides 0
    if (b == 0):
         return a
    return gcd(b, a%b)
  
# Function to find the minimum
# sum of array
def minSum(A, N) :
  
    min = sys.maxsize
     
    for i in range(0, N-1, 1):
        b = gcd(A[i], A[i + 1])
        if (b < min) :
            min = b
   
    return min * N
 
  
# Driver Code
 
A = [ 3, 3, 9 ]
N = len(A)
  
# Function call
print(minSum(A, N))
 
# This code is contributed by code_hunt.


C#




// C# code to implement the approach
using System;
class GFG
{
 
  // Function to find gcd of two numbers
  public static int gcd(int p, int q)
  {
    if (q == 0) {
      return p;
    }
    return gcd(q, p % q);
  }
 
  // Function to find the minimum
  // sum of array
  public static int minSum(int[] A, int N)
  {
    int min = Int32.MaxValue;
    for (int i = 0; i < N - 1; i++) {
      int b = gcd(A[i], A[i + 1]);
      if (b < min)
        min = b;
    }
    return min * N;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int[] A = { 3, 3, 9 };
    int N = A.Length;
 
    // Function call
    Console.WriteLine(minSum(A, N));
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
// Javascript code to implement the approach
 
// Function to find gcd of two numbers
function gcd(a, b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Function to find the minimum
// sum of array
function minSum(A,N)
{
    let min = Number.MAX_SAFE_INTEGER;
        for (let i = 0; i < N - 1; i++) {
            let b = gcd(A[i], A[i + 1]);
            if (b < min)
                min = b;
        }
        return min * N;
}
 
// Driver code
        let A = [ 3, 3, 9 ];
        let N = A.length;
 
        // Function call
        console.log(minSum(A, N));
 
// This code is contributed by aarohirai2616.
</script>


Output

9

Time Complexity: O(N) 
Auxiliary Space: O(1) 



Similar Reads

Minimize the maximum of Array by replacing any element with other element at most K times
Given an array arr[] of size N and an integer K, the task is to minimize the value of the maximum element of the array arr[] after replacing any element of the array with any other element of that array at most K times. Examples: Input: arr[] = {5, 3, 3, 2, 1}, K = 3Output: 2Explanation: Replace the elements at index 0, 1 and 2 with the value 1.The
8 min read
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum
Given an array arr[] of size N and an integer K, the task is to find the minimum cost required to reduce given array to a single element, where cost of replacing K consecutive array elements by their sum is equal to the sum of the K consecutive elements. If it is not possible to reduce given array to a single element, then print -1. Examples: Input
10 min read
Minimize remaining array element by repeatedly replacing pairs by half of one more than their sum
Given an array arr[] containing a permutation of first N natural numbers. In one operation, remove a pair (X, Y) from the array and insert (X + Y + 1) / 2 into the array. The task is to find the smallest array element that can be left remaining in the array by performing the given operation exactly N - 1 times and the N - 1 pairs. If multiple solut
11 min read
Minimize sum of absolute differences between given Arrays by replacing at most 1 element from first Array
Given two arrays a[] and b[] of equal size. The task is to calculate the minimum sum of absolute differences for each index. It is allowed to replace at most 1 element of the first array with any value from the first array itself. Example: Input: a[] = {1, 9, 4, 2}, b[] = {2, 3, 7, 1}Output: 6Explanation: Change the value of a[1] = 4 or 2. The mini
9 min read
Maximum possible GCD after replacing at most one element in the given array
Given an array arr[] of size N &gt; 1. The task is to find the maximum possible GCD of the array by replacing at most one element.Examples: Input: arr[] = {6, 7, 8} Output: 2 Replace 7 with 2 and gcd(6, 2, 8) = 2 which is maximum possible.Input: arr[] = {12, 18, 30} Output: 6 Approach: Idea is to find the GCD value of all the sub-sequences of lengt
9 min read
Modify array by replacing each element with nearest power of GCD of all previous elements
Given an array arr[] consisting of N positive integers, the task is to replace each array element with the nearest power of GCD of all the preceding array elements. If there exists more than one possible answer, then print any one of them. Examples: Input: arr[] = {4, 2, 8, 2}Output: 4 1 8 2Explanation: For element arr[0], the element remains the s
9 min read
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum
Given an integer array arr[], the task is to minimize the length of the given array by repeatedly replacing two unequal adjacent array elements by their sum. Once the array is reduced to its minimum possible length, i.e. no adjacent unequal pairs are remaining in the array, print the count of operations required. Examples: Input: arr[] = {2, 1, 3,
6 min read
Minimize Y for given N to minimize difference between LCM and GCD
Given an integer N, the task is to find a minimum possible Y that satisfies the following condition: Y &gt; N.Y is not divisible by N (except N = 1).The absolute difference of gcd and lcm of N and Y i.e. | gcd(N, Y)?lcm(N, Y) | is as minimum as possible Examples: Input: N = 3 Output: 4?Explanation: When Y = 4 is taken then GCD(3, 4) = 1 and LCM(3,
5 min read
Minimize swaps required to maximize the count of elements replacing a greater element in an Array
Given an array A[], consisting of N elements, the task is to find the minimum number of swaps required such that array elements swapped to replace a higher element, in the original array, are maximized. Examples: Input: A[] = {4, 3, 3, 2, 5} Output: 3 Explanation: Swap 1: {4, 3, 3, 2, 5} -&gt; {5, 3, 3, 2, 4} Swap 2: {5, 3, 3, 2, 4} -&gt; {3, 3, 5,
10 min read
Minimize remaining array element by removing pairs and replacing them by their absolute difference
Given an array arr[] consisting of N positive integers, the task is to minimize the remaining array element that can be obtained by repeatedly removing a pair of array elements and replacing them by their absolute difference. Examples: Input: arr[] ={ 2, 7, 4, 1, 8, 1 } Output: 1 Explanation: Removing the pair (arr[0], arr[2]) from arr[] and insert
15 min read
Article Tags :
Practice Tags :