Check if all array elements are pairwise co-prime or not - GeeksforGeeks

02 Jun, 2021
Given an array A[] consisting of N positive integers, the task is to check if all the array elements are pairwise co-prime, i.e. for all pairs (Ai , Aj), such that 1<=i<j<=N, GCD(Ai, Aj) = 1.
Examples: 
Input : A[] = {2, 3, 5}Output : YesExplanation : All the pairs, (2, 3), (3, 5), (2, 5) are pairwise co-prime.
Input : A[] = {5, 10}Output : NoExplanation : GCD(5, 10)=5 so they are not co-prime.
Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from a given array and for each pair, check if it is coprime or not. If any pair is found to be non-coprime, print “No“. Otherwise, print “Yes“.Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observation: 
If any two numbers have a common prime factor, then their GCD can never be 1.  
This can also be interpreted as: 
The LCM of the array must be equal to the product of the elements in the array.
Therefore, the solution boils down to calculating the LCM of the given array and check if it is equal to the product of all the array elements or not.
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to calculate GCDll GCD(ll a, ll b){    if (a == 0)        return b;    return GCD(b % a, a);} // Function to calculate LCMll LCM(ll a, ll b){    return (a * b)        / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimevoid checkPairwiseCoPrime(int A[], int n){    // Initialize variables    ll prod = 1;    ll lcm = 1;     // Iterate over the array    for (int i = 0; i < n; i++) {         // Calculate product of        // array elements        prod *= A[i];         // Calculate LCM of        // array elements        lcm = LCM(A[i], lcm);    }     // If the product of array elements    // is equal to LCM of the array    if (prod == lcm)        cout << "Yes" << endl;    else        cout << "No" << endl;}// Driver Codeint main(){    int A[] = { 2, 3, 5 };    int n = sizeof(A) / sizeof(A[0]);     // Function call    checkPairwiseCoPrime(A, n);}
// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to calculate GCDstatic long GCD(long a, long b){    if (a == 0)        return b;             return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a, long b){    return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int A[], int n){         // Initialize variables    long prod = 1;    long lcm = 1;     // Iterate over the array    for(int i = 0; i < n; i++)    {                 // Calculate product of        // array elements        prod *= A[i];         // Calculate LCM of        // array elements        lcm = LCM(A[i], lcm);    }         // If the product of array elements    // is equal to LCM of the array    if (prod == lcm)        System.out.println("Yes");    else        System.out.println("No");} // Driver Codepublic static void main (String[] args){    int A[] = { 2, 3, 5 };    int n = A.length;         // Function call    checkPairwiseCoPrime(A, n);}} // This code is contributed by offbeat
# Python3 program for the above approach # Function to calculate GCDdef GCD(a, b):         if (a == 0):        return b             return GCD(b % a, a) # Function to calculate LCMdef LCM(a, b):         return (a * b) // GCD(a, b) # Function to check if aelements# in the array are pairwise coprimedef checkPairwiseCoPrime(A, n):         # Initialize variables    prod = 1    lcm = 1     # Iterate over the array    for i in range(n):         # Calculate product of        # array elements        prod *= A[i]         # Calculate LCM of        # array elements        lcm = LCM(A[i], lcm)     # If the product of array elements    # is equal to LCM of the array    if (prod == lcm):        print("Yes")    else:        print("No") # Driver Codeif __name__ == '__main__':         A = [ 2, 3, 5 ]    n = len(A)     # Function call    checkPairwiseCoPrime(A, n) # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to calculate GCDstatic long GCD(long a,                long b){  if (a == 0)    return b;  return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a,                long b){  return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int []A,                                 int n){      // Initialize variables  long prod = 1;  long lcm = 1;   // Iterate over the array  for(int i = 0; i < n; i++)  {    // Calculate product of    // array elements    prod *= A[i];     // Calculate LCM of    // array elements    lcm = LCM(A[i], lcm);  }   // If the product of array elements  // is equal to LCM of the array  if (prod == lcm)    Console.WriteLine("Yes");  else    Console.WriteLine("No");} // Driver Codepublic static void Main(String[] args){  int []A = {2, 3, 5};  int n = A.Length;   // Function call  checkPairwiseCoPrime(A, n);}} // This code is contributed by Rajput-Ji
<script>// javascript program for the above approach   // Function to calculate GCD    function GCD(a , b) {        if (a == 0)            return b;         return GCD(b % a, a);    }     // Function to calculate LCM    function LCM(a , b) {        return (a * b) / GCD(a, b);    }     // Function to check if all elements    // in the array are pairwise coprime    function checkPairwiseCoPrime(A , n) {         // Initialize variables        var prod = 1;        var lcm = 1;         // Iterate over the array        for (i = 0; i < n; i++) {             // Calculate product of            // array elements            prod *= A[i];             // Calculate LCM of            // array elements            lcm = LCM(A[i], lcm);        }         // If the product of array elements        // is equal to LCM of the array        if (prod == lcm)            document.write("Yes");        else            document.write("No");    }     // Driver Code             var A = [ 2, 3, 5 ];        var n = A.length;         // Function call        checkPairwiseCoPrime(A, n); // This code contributed by umadevi9616</script>
Yes
Time Complexity: O(N log (min(A[i])))Auxiliary Space: O(1)
mohit kumar 29
offbeat
Rajput-Ji
umadevi9616
arorakashish0911
surinderdawra388
GCD-LCM
prime-factor
Arrays
Greedy
Mathematical
Searching
Arrays
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3