Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Minimize count of integers to be added in Array to make each adjacent pairs co-prime

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an integer array arr[] of N integers, the task is to 
make each adjacent pair in the array co prime, by adding minimum number of integers in the array. Return -1 if not possible.

Example: 

Input: N = 2, arr = [7, 42]
Output: 1
Explanation: After adding 11, the final array will be [7, 11, 42]. All adjacent elements are now coprime

Input: N = 4, arr = [2200, 42, 2184, 17]
Output: 3
Explanation: 43, 2195, 2199 can be added in the current array. The final sorted array will be [17, 42, 43, 2184, 2195, 2199, 2200] and all adjacent pairs are coprime.

 

Approach: Given problem can be solved by making some observations and basic number theory. Below steps can be followed:

  • Sort the array in non-decreasing order
  • Iterate from left to right and check each adjacent pair for the following conditions:
  • If the current pair is coprime then there is no need to add any extra element
  • If the current pair is not coprime then iterate for all values between the elements and check if the current value is coprime with both left and right pairs.
  • Otherwise, it is always possible to add two values that are coprime with each other and with left and right values respectively.

Below is the implementation of the above approach:

C++




// C++ implementation for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate minimum additions
// required such that no adjacent pairs are
// coprime in their sorted order
int MinimumAdditions(int arr[], int n)
{
    // Sort the given array
    // in non-decreasing order
    sort(arr, arr + n);
 
    // First check if any two adjacent
    // elements are same then
    // the answer will be -1
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1]) {
 
            // Return directly from here
            return -1;
        }
    }
 
    // Variable to store the answer
    int ans = 0;
 
    for (int i = 1; i < n; i++) {
        if (__gcd(arr[i],
                  arr[i - 1])
            == 1) {
            continue;
        }
 
        // Check for a single middle element
        // Maintain a bool value
        bool found = 0;
 
        for (int j = arr[i - 1] + 1;
             j <= arr[i] - 1; j++) {
            if (__gcd(arr[i - 1], j) == 1
                && __gcd(j, arr[i]) == 1) {
                found = 1;
            }
        }
        if (found) {
            ans++;
        }
        else {
            ans += 2;
        }
    }
 
    // return the answer
    return ans;
}
 
// Driver Code
int main()
{
    int N = 4;
    int arr[] = { 2200, 42, 2184, 17 };
    cout << MinimumAdditions(arr, N);
}


Java




// Java implementation for the above approach
import java.io.*;
import java.util.Arrays;
 
class GFG{
 
static int gcd(int a, int b)
{
    return b == 0 ? a : gcd(b, a % b);
}
 
// Function to calculate minimum additions
// required such that no adjacent pairs are
// coprime in their sorted order
static int MinimumAdditions(int []arr, int n)
{
    // Sort the given array
    // in non-decreasing order
    Arrays.sort(arr);
 
    // First check if any two adjacent
    // elements are same then
    // the answer will be -1
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1]) {
 
            // Return directly from here
            return -1;
        }
    }
 
    // Variable to store the answer
    int ans = 0;
 
    for (int i = 1; i < n; i++) {
        if (gcd(arr[i],
                  arr[i - 1])
            == 1) {
            continue;
        }
 
        // Check for a single middle element
        // Maintain a bool value
        int found = 0;
 
        for (int j = arr[i - 1] + 1;
             j <= arr[i] - 1; j++) {
            if (gcd(arr[i - 1], j) == 1
                && gcd(j, arr[i]) == 1) {
                found = 1;
            }
        }
        if (found!=0) {
            ans++;
        }
        else {
            ans += 2;
        }
    }
 
    // return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
    {
    int N = 4;
    int []arr = { 2200, 42, 2184, 17 };
    System.out.println(MinimumAdditions(arr, N));
}
}
 
// This code is contributed by shivanisinghss2110


Python3




# Python 3 implementation for the above approach
import math
 
# Function to calculate minimum additions
# required such that no adjacent pairs are
# coprime in their sorted order
def MinimumAdditions(arr, n):
 
    # Sort the given array
    # in non-decreasing order
    arr.sort()
 
    # First check if any two adjacent
    # elements are same then
    # the answer will be -1
    for i in range(1,  n):
        if (arr[i] == arr[i - 1]):
 
            # Return directly from here
            return -1
 
    # Variable to store the answer
    ans = 0
 
    for i in range(1, n):
        if (math.gcd(arr[i],
                     arr[i - 1])
                == 1):
            continue
 
        # Check for a single middle element
        # Maintain a bool value
        found = 0
 
        for j in range(arr[i - 1] + 1,
                       arr[i]):
            if (math.gcd(arr[i - 1], j) == 1
                    and math.gcd(j, arr[i]) == 1):
                found = 1
 
        if (found):
            ans += 1
 
        else:
            ans += 2
 
    # return the answer
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    N = 4
    arr = [2200, 42, 2184, 17]
    print(MinimumAdditions(arr, N))
 
    # This code is contributed by ukasp.


C#




// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
static int gcd(int a, int b)
{
    return b == 0 ? a : gcd(b, a % b);
}
 
// Function to calculate minimum additions
// required such that no adjacent pairs are
// coprime in their sorted order
static int MinimumAdditions(int []arr, int n)
{
    // Sort the given array
    // in non-decreasing order
    Array.Sort(arr);
 
    // First check if any two adjacent
    // elements are same then
    // the answer will be -1
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1]) {
 
            // Return directly from here
            return -1;
        }
    }
 
    // Variable to store the answer
    int ans = 0;
 
    for (int i = 1; i < n; i++) {
        if (gcd(arr[i],
                  arr[i - 1])
            == 1) {
            continue;
        }
 
        // Check for a single middle element
        // Maintain a bool value
        int found = 0;
 
        for (int j = arr[i - 1] + 1;
             j <= arr[i] - 1; j++) {
            if (gcd(arr[i - 1], j) == 1
                && gcd(j, arr[i]) == 1) {
                found = 1;
            }
        }
        if (found!=0) {
            ans++;
        }
        else {
            ans += 2;
        }
    }
 
    // return the answer
    return ans;
}
 
// Driver Code
public static void Main()
{
    int N = 4;
    int []arr = { 2200, 42, 2184, 17 };
    Console.Write(MinimumAdditions(arr, N));
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




<script>
       // JavaScript Program to implement
       // the above approach
       // Recursive function to return gcd of a and b
       function __gcd(a, b) {
           // Everything divides 0
           if (a == 0)
               return b;
           if (b == 0)
               return a;
 
           // base case
           if (a == b)
               return a;
 
           // a is greater
           if (a > b)
               return __gcd(a - b, b);
           return __gcd(a, b - a);
       }
 
       // Function to calculate minimum additions
       // required such that no adjacent pairs are
       // coprime in their sorted order
       function MinimumAdditions(arr, n) {
           // Sort the given array
           // in non-decreasing order
           arr.sort(function (a, b) { return a - b; });
 
           // First check if any two adjacent
           // elements are same then
           // the answer will be -1
           for (let i = 1; i < n; i++) {
               if (arr[i] == arr[i - 1]) {
 
                   // Return directly from here
                   return -1;
               }
           }
 
           // Variable to store the answer
           let ans = 0;
 
           for (let i = 1; i < n; i++) {
               if (__gcd(arr[i],
                   arr[i - 1])
                   == 1) {
                   continue;
               }
 
               // Check for a single middle element
               // Maintain a bool value
               let found = 0;
 
               for (let j = arr[i - 1] + 1;
                   j <= arr[i] - 1; j++) {
                   if (__gcd(arr[i - 1], j) == 1
                       && __gcd(j, arr[i]) == 1) {
                       found = 1;
                   }
               }
               if (found) {
                   ans++;
               }
               else {
                   ans += 2;
               }
           }
 
           // return the answer
           return ans;
       }
 
       // Driver Code
 
       let N = 4;
       let arr = [2200, 42, 2184, 17];
       document.write(MinimumAdditions(arr, N));
 
 
    // This code is contributed by Potta Lokesh
 
   </script>


Output

3

Time Complexity: O(Nlog(N) + M), where M is maximum element in array
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Last Updated : 15 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials