Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the minimum possible health of the winning player
Next article icon

Minimum insertions to make a Co-prime array

Last Updated : 10 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.
Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, gcd(a, b) = 1      .

Examples : 

Input :  A[] = {2, 7, 28}
Output : 1
Explanation : 
Here, 1st pair = {2, 7} are co-primes( gcd(2, 7) = 1).
2nd pair = {7, 28} are not co-primes, insert 9
between them. gcd(7, 9) = 1 and gcd(9, 28) = 1.

Input : A[] = {5, 10, 20}
Output : 2
Explanation : 
Here, there is no pair which are co-primes. 
Insert 7 between (5, 10) and 1 between (10, 20).

Recommended Practice
Make Co-prime Array
Try It!

Observe that to make a pair to become co-primes we have to insert a number which makes the newly formed pairs co-primes. So, we have to check every adjacent pair for their co-primality and insert a number if required. Now, what is the number that should be inserted? Let us take two numbers a and b. If any of a or b is 1, then GCD(a, b) = 1. So, we can insert ONE(1) at every pair. For efficiency we use euler’s gcd function .

Below is the implementation of the above approach:  

C++

// CPP program for minimum insertions to
// make a Co-prime Array.
#include <bits/stdc++.h>
using namespace std;
 
void printResult(int arr[], int n)
{
    // Counting adjacent pairs that are not
    // co-prime.
    int count = 0;
    for (int i = 1; i < n; i++)    
        if (__gcd(arr[i], arr[i - 1]) != 1)
            count++;
 
    cout << count << endl; // No.of insertions
    cout << arr[0] << " ";
    for (int i = 1; i < n; i++)
    {
        // If pair is not a co-prime insert 1.
        if (__gcd(arr[i], arr[i - 1]) != 1)
            cout << 1 << " ";
        cout << arr[i] << " ";
    }
}
 
// Driver Function
int main()
{
    int A[] = { 5, 10, 20 };
    int n = sizeof(A) / sizeof(A[0]);
    printResult(A, n);
    return 0;
}
                      
                       

Java

//Java program for minimum insertions
// to make a Co-prime Array.
import java.io.*;
 
class GFG {
     
    // Recursive function to return
    // gcd of a and b
    static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0 || b == 0)
        return 0;
     
        // base case
        if (a == b)
            return a;
     
        // a is greater
        if (a > b)
            return gcd(a-b, b);
 
        return gcd(a, b-a);
    }
     
    static void printResult(int arr[], int n)
    {
         
        // Counting adjacent pairs that are not
        // co-prime.
        int count = 0;
 
        for (int i = 1; i < n; i++)    
            if (gcd(arr[i], arr[i - 1]) != 1)
                count++;
     
        // No.of insertions
        System.out.println(count );
        System.out.print (arr[0] + " ");
 
        for (int i = 1; i < n; i++)
        {
             
            // If pair is not a co-prime insert 1.
            if (gcd(arr[i], arr[i - 1]) != 1)
                System.out.print( 1 + " ");
            System.out.print(arr[i] + " ");
        }
    }
     
    // Driver Function
    public static void main(String args[])
    {
        int A[] = { 5, 10, 20 };
        int n = A.length;
        printResult(A, n);
    }
}
 
/*This code is contributed by Nikita Tiwari.*/
                      
                       

Python3

# Python3 code for minimum insertions
# to make a Co-prime Array.
from fractions import gcd
 
def printResult(arr, n):
 
    # Counting adjacent pairs that
    # are not co-prime.
    count = 0
    for i in range(1,n):
        if (gcd(arr[i], arr[i - 1]) != 1):
            count+=1
     
    print(count)     # No.of insertions
    print( arr[0], end = " ")
    for i in range(1,n):
         
        # If pair is not a co-prime insert 1.
        if (gcd(arr[i], arr[i - 1]) != 1):
            print(1, end = " ")
        print(arr[i] , end = " ")
         
# Driver Code
A = [ 5, 10, 20 ]
n = len(A)
printResult(A, n)
 
# This code is contributed by "Sharad_Bhardwaj".
                      
                       

C#

// C# program for minimum insertions
// to make a Co-prime Array.
using System;
 
class GFG {
 
    // Recursive function to return
    // gcd of a and b
    static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
 
        // base case
        if (a == b)
            return a;
 
        // a is greater
        if (a > b)
            return gcd(a - b, b);
 
        return gcd(a, b - a);
    }
 
    static void printResult(int[] arr, int n)
    {
        // Counting adjacent pairs that
        // are not co-prime.
        int count = 0;
 
        for (int i = 1; i < n; i++)
            if (gcd(arr[i], arr[i - 1]) != 1)
                count++;
 
        // No.of insertions
        Console.WriteLine(count);
        Console.Write(arr[0] + " ");
 
        for (int i = 1; i < n; i++) {
 
            // If pair is not a co-prime insert 1.
            if (gcd(arr[i], arr[i - 1]) != 1)
                Console.Write(1 + " ");
            Console.Write(arr[i] + " ");
        }
    }
 
    // Driver Function
    public static void Main()
    {
        int[] A = { 5, 10, 20 };
        int n = A.Length;
        printResult(A, n);
    }
}
 
/*This code is contributed by vt_m.*/
                      
                       

PHP

<?php
// PHP program for minimum
// insertions to make a
// Co-prime Array.
 
// Recursive function to
// return gcd of a and b
function gcd($a, $b)
{
    // Everything divides 0
    if ($a == 0 || $b == 0)
        return 0;
 
    // base case
    if ($a == $b)
        return $a;
 
    // a is greater
    if ($a > $b)
        return gcd($a - $b, $b);
 
    return gcd($a, $b - $a);
}
 
function printResult($arr, $n)
{
    // Counting adjacent pairs
    // that are not co-prime.
    $count = 0;
 
    for ($i = 1; $i < $n; $i++)
        if (gcd($arr[$i],
                $arr[$i - 1]) != 1)
            $count++;
 
    // No.of insertions
    echo $count, "\n";
    echo $arr[0] , " ";
 
    for ($i = 1; $i < $n; $i++)
    {
 
        // If pair is not a
        // co-prime insert 1.
        if (gcd($arr[$i],
                $arr[$i - 1]) != 1)
            echo 1 , " ";
        echo $arr[$i] , " ";
    }
}
 
// Driver Code
$A = array(5, 10, 20);
$n = sizeof($A);
printResult($A, $n);
 
// This code is contributed
// by ajit
?>
                      
                       

Javascript

<script>
 
// Javascript program for minimum insertions
// to make a Co-prime Array.
 
// Recursive function to return
// gcd of a and b
function gcd(a, b)
{
     
    // Everything divides 0
    if (a == 0 || b == 0)
        return 0;
 
    // base case
    if (a == b)
        return a;
 
    // a is greater
    if (a > b)
        return gcd(a - b, b);
 
    return gcd(a, b - a);
}
 
function printResult(arr, n)
{
     
    // Counting adjacent pairs that
    // are not co-prime.
    let count = 0;
 
    for(let i = 1; i < n; i++)
        if (gcd(arr[i], arr[i - 1]) != 1)
            count++;
 
    // No.of insertions
    document.write(count + "</br>");
    document.write(arr[0] + " ");
 
    for(let i = 1; i < n; i++)
    {
         
        // If pair is not a co-prime insert 1.
        if (gcd(arr[i], arr[i - 1]) != 1)
            document.write(1 + " ");
             
        document.write(arr[i] + " ");
    }
}
 
// Driver code
let A = [ 5, 10, 20 ];
let n = A.length;
 
printResult(A, n);
 
// This code is contributed by suresh07
 
</script>
                      
                       

Output
2 5 1 10 1 20 

Time Complexity: O(n log(Ai)), for using __gcd function
Auxiliary Space: O(1)



Next Article
Find the minimum possible health of the winning player

H

Harsha_Mogali
Improve
Article Tags :
  • Arrays
  • DSA
  • euler-totient
  • GCD-LCM
  • Prime Number
Practice Tags :
  • Arrays
  • Prime Number

Similar Reads

  • GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
    GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers. Fastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorith
    4 min read
  • Program to Find GCD or HCF of Two Numbers
    Given two numbers a and b, the task is to find the GCD of the two numbers. Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples: Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4, 5, 10
    15+ min read
  • Check if two numbers are co-prime or not
    Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : Input : 2 3Output : Co-PrimeInput : 4 8Output : Not Co-Prime The idea is simple, we find GCD of two numbers
    5 min read
  • GCD of more than two (or array) numbers
    Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number. Examples: Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2 Using Recursive GCDThe GCD of three or more numbers equals the product of the
    11 min read
  • Program to find LCM of two numbers
    LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 12, b = 18Output : 3636 is the smallest number divisible by both 12 and 18 Input : a = 5, b = 11Output : 5555 is the smallest number divisible by both 5 and 11 [Naive Approach] Using Conditional Loop This app
    8 min read
  • LCM of given array elements
    In this article, we will learn how to find the LCM of given array elements. Given an array of n numbers, find the LCM of it. Example: Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252 Table of Content [Naive Approach] Iterative LCM Calculation - O(n * log(m
    15 min read
  • Find the other number when LCM and HCF given
    Given a number A and L.C.M and H.C.F. The task is to determine the other number B. Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula: A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60
    4 min read
  • Minimum insertions to make a Co-prime array
    Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, [Tex]gcd(a, b) = 1 [/Tex]. Examples : Input : A[] = {2, 7, 28}Ou
    7 min read
  • Find the minimum possible health of the winning player
    Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winn
    4 min read
  • Minimum squares to evenly cut a rectangle
    Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not min
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences