Check if all the pairs of an array are coprime with each other

Given an array arr[], the task is to check if all the pairs of an array are coprime to each other. All pairs of an array are coprime when GCD(arr[i], arr[j]) = 1 holds for every pair (i, j), such that 1? i < j ? N.
Examples:
Input: arr[] = {1, 3, 8}
Output: Yes
Explanation:
Here, GCD(arr[0], arr[1]) = GCD(arr[0], arr[2]) = GCD(arr[1], arr[2]) = 1
Hence, all the pairs are coprime to each other.Input: arr[] = {6, 67, 24, 1}
Output: No
Naive Approach: A simple solution is to iterate over every pair (A[i], A[j]) from the given array and check if the gcd(A[i], A[j]) = 1 or not. Therefore, the only positive integer(factor) that divides both of them is 1.
Below is the implementation of the naive approach:
C++
// C++ implementation of the// above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to check if all the// pairs of the array are coprime// with each other or notbool allCoprime(int A[], int n){Â Â Â Â bool all_coprime = true;Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â Â Â for (int j = i + 1; j < n; j++) {Â
            // Check if GCD of the            // pair is not equal to 1            if (__gcd(A[i], A[j]) != 1) {Â
                // All pairs are non-coprime                // Return false                all_coprime = false;                break;            }        }    }    return all_coprime;}Â
// Driver Codeint main(){Â Â Â Â int A[] = { 3, 5, 11, 7, 19 };Â Â Â Â int arr_size = sizeof(A) / sizeof(A[0]);Â Â Â Â if (allCoprime(A, arr_size)) {Â Â Â Â Â Â Â Â cout << "Yes";Â Â Â Â }Â Â Â Â else {Â Â Â Â Â Â Â Â cout << "No";Â Â Â Â }Â Â Â Â return 0;} |
Java
// Java implementation of the // above approach import java.util.*;import java.lang.*;Â
class GFG{Â
// Function to check if all the // pairs of the array are coprime // with each other or not static boolean allCoprime(int A[], int n) {     boolean all_coprime = true;     for(int i = 0; i < n; i++)    {         for(int j = i + 1; j < n; j++)         {                          // Check if GCD of the             // pair is not equal to 1             if (gcd(A[i], A[j]) != 1)            {                                  // All pairs are non-coprime                 // Return false                 all_coprime = false;                 break;             }         }     }     return all_coprime; } Â
// Function return gcd of two numberstatic int gcd(int a, int b) { Â Â Â Â if (b == 0) Â Â Â Â Â Â Â Â return a; Â Â Â Â Â Â Â Â Â Â Â Â Â return gcd(b, a % b); }Â
// Driver Codepublic static void main (String[] args){    int A[] = { 3, 5, 11, 7, 19 };     int arr_size = A.length;          if (allCoprime(A, arr_size))    {         System.out.println("Yes");     }     else    {         System.out.println("No");     } }}Â
// This code is contributed by offbeat |
Python3
# Python3 implementation of the# above approachdef gcd(a, b):          if (b == 0):         return a     else:         return gcd(b, a % b)   # Function to check if all the# pairs of the array are coprime# with each other or notdef allCoprime(A, n):          all_coprime = True          for i in range(n):        for j in range(i + 1, n):                          # Check if GCD of the            # pair is not equal to 1            if gcd(A[i], A[j]) != 1:                   # All pairs are non-coprime                # Return false                all_coprime = False;                break          return all_coprimeÂ
# Driver code  if __name__=="__main__":          A = [ 3, 5, 11, 7, 19 ]    arr_size = len(A)         if (allCoprime(A, arr_size)):        print('Yes')    else:        print('No')Â
# This code is contributed by rutvik_56 |
C#
// C# implementation of the // above approach using System;class GFG{Â
// Function to check if all the // pairs of the array are coprime // with each other or not static bool allCoprime(int []A,                        int n) {   bool all_coprime = true;   for(int i = 0; i < n; i++)  {     for(int j = i + 1; j < n; j++)     {       // Check if GCD of the       // pair is not equal to 1       if (gcd(A[i], A[j]) != 1)      {         // All pairs are non-coprime         // Return false         all_coprime = false;         break;       }     }   }   return all_coprime; } Â
// Function return gcd of two numberstatic int gcd(int a, int b) { Â Â if (b == 0) Â Â Â Â return a; Â
  return gcd(b, a % b); }Â
// Driver Codepublic static void Main(String[] args){Â Â int []A = {3, 5, 11, 7, 19}; Â Â int arr_size = A.Length; Â
  if (allCoprime(A, arr_size))  {     Console.WriteLine("Yes");   }   else  {     Console.WriteLine("No");   } }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// JavaScript implementation of the// above approachÂ
function gcd(a, b) {Â Â if (!b) {Â Â Â Â return a;Â Â }Â
  return gcd(b, a % b);}Â
// Function to check if all the// pairs of the array are coprime// with each other or notfunction allCoprime( A, n){Â Â Â Â var all_coprime = true;Â Â Â Â for (var i = 0; i < n; i++) {Â Â Â Â Â Â Â Â for (var j = i + 1; j < n; j++) {Â
            // Check if GCD of the            // pair is not equal to 1            if (gcd(A[i], A[j]) != 1) {Â
                // All pairs are non-coprime                // Return false                all_coprime = false;                break;            }        }    }    return all_coprime;}Â
/* Driver Program */Â
var A = [ 3, 5, 11, 7, 19 ];var arr_size = A.length;if (allCoprime(A, arr_size)) {Â Â Â Â console.log("Yes");}else {Â Â Â Â console.log( "No");}Â
// This code is contributed by ukasp.</script> |
Yes
 Time Complexity: O(N2 logN)
Auxiliary Space: O(1)
Efficient Approach: The key observation in the problem is that two numbers are said to be co-prime if only positive integer(factor) that divides both of them is 1. So, we can store the factors of each element of the array in the container(set, array, etc.) including this element, and check if this factor is already present or not.
Illustration:Â
For the array arr[] = {6, 5, 10, 3}Â
Since the pairs (6, 10), (6, 3) and (5, 10) have common factors, all pairs from the array are not coprime with each other.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the// above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to store and// check the factorsbool findFactor(int value,                unordered_set<int>& factors){    factors.insert(value);    for (int i = 2; i * i <= value; i++) {        if (value % i == 0) {Â
            // Check if factors are equal            if (value / i == i) {Â
                // Check if the factor is                // already present                if (factors.find(i)                    != factors.end()) {                    return true;                }                else {Â
                    // Insert the factor in set                    factors.insert(i);                }            }            else {Â
                // Check if the factor is                // already present                if (factors.find(i) != factors.end()                    || factors.find(value / i)                           != factors.end()) {                    return true;                }                else {Â
                    // Insert the factors in set                    factors.insert(i);                    factors.insert(value / i);                }            }        }    }    return false;}Â
// Function to check if all the// pairs of array elements// are coprime with each otherbool allCoprime(int A[], int n){Â Â Â Â bool all_coprime = true;Â Â Â Â unordered_set<int> factors;Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â Â Â if (A[i] == 1)Â Â Â Â Â Â Â Â Â Â Â Â continue;Â
        // Check if factors of A[i]        // haven't occurred previously        if (findFactor(A[i], factors)) {            all_coprime = false;            break;        }    }    return all_coprime;}Â
// Driver Codeint main(){Â Â Â Â int A[] = { 3, 5, 11, 7, 19 };Â Â Â Â int arr_size = sizeof(A) / sizeof(A[0]);Â Â Â Â if (allCoprime(A, arr_size)) {Â Â Â Â Â Â Â Â cout << "Yes";Â Â Â Â }Â Â Â Â else {Â Â Â Â Â Â Â Â cout << "No";Â Â Â Â }Â Â Â Â return 0;} |
Java
// Java implementation of // the above approachimport java.util.*;class GFG{Â
// Function to store and// check the factorsstatic boolean findFactor(int value,                          HashSet<Integer> factors){  factors.add(value);  for (int i = 2; i * i <= value; i++)   {    if (value % i == 0)     {      // Check if factors are equal      if (value / i == i)       {        // Check if the factor is        // already present        if (factors.contains(i))         {          return true;        }        else        {          // Insert the factor in set          factors.add(i);        }      }      else      {        // Check if the factor is        // already present        if (factors.contains(i) ||             factors.contains(value / i))         {          return true;        }        else        {          // Insert the factors in set          factors.add(i);          factors.add(value / i);        }      }    }  }  return false;}Â
// Function to check if all the// pairs of array elements// are coprime with each otherstatic boolean allCoprime(int A[], int n){Â Â boolean all_coprime = true;Â Â HashSet<Integer> factors = Â Â Â Â Â Â Â Â Â Â new HashSet<Integer>();Â Â for (int i = 0; i < n; i++) Â Â {Â Â Â Â if (A[i] == 1)Â Â Â Â Â Â continue;Â
    // Check if factors of A[i]    // haven't occurred previously    if (findFactor(A[i], factors))     {      all_coprime = false;      break;    }  }  return all_coprime;}Â
// Driver Codepublic static void main(String[] args){  int A[] = {3, 5, 11, 7, 19};  int arr_size = A.length;  if (allCoprime(A, arr_size))   {    System.out.print("Yes");  }  else  {    System.out.print("No");  }}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python3 implementation of # the above approachÂ
# Function to store and# check the factorsdef findFactor(value, factors):Â
    factors.add(value)    i = 2    while(i * i <= value):             if value % i == 0:                     # Check if factors are equal            if value // i == i:                             # Check if the factor is              # already present              if i in factors:                  return bool(True)              else:                                   # Insert the factor in set                  factors.add(i)            else:                                  # Check if the factor is                # already present                if (i in factors) or                   ((value // i) in factors):                                 return bool(True)                               else :                                   # Insert the factors in set                  factors.add(i)                  factors.add(value // i)                         i += 1         return bool(False)Â
# Function to check if all the# pairs of array elements# are coprime with each otherdef allCoprime(A, n):Â
  all_coprime = bool(True)  factors = set()     for i in range(n):         if A[i] == 1:        continue      # Check if factors of A[i]    # haven't occurred previously    if findFactor(A[i], factors):         all_coprime = bool(False)      break     return bool(all_coprime)  # Driver codeA = [3, 5, 11, 7, 19]arr_size = len(A)Â
if (allCoprime(A, arr_size)): Â Â Â Â print("Yes")else:Â Â Â Â print("No")Â
# This code is contributed by divyeshrabadiya07 |
C#
// C# implementation of // the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Function to store and// check the factorsstatic bool findFactor(int value,               HashSet<int> factors){    factors.Add(value);    for(int i = 2; i * i <= value; i++)     {        if (value % i == 0)         {                         // Check if factors are equal            if (value / i == i)             {                                 // Check if the factor is                // already present                if (factors.Contains(i))                 {                    return true;                }                else                {                                         // Insert the factor in set                    factors.Add(i);                }            }            else            {                                 // Check if the factor is                // already present                if (factors.Contains(i) ||                     factors.Contains(value / i))                 {                    return true;                }                else                {                    // Insert the factors in set                    factors.Add(i);                    factors.Add(value / i);                }            }        }    }    return false;}Â
// Function to check if all the// pairs of array elements// are coprime with each otherstatic bool allCoprime(int []A, int n){    bool all_coprime = true;    HashSet<int> factors = new HashSet<int>();         for(int i = 0; i < n; i++)     {        if (A[i] == 1)            continue;                     // Check if factors of A[i]        // haven't occurred previously        if (findFactor(A[i], factors))         {            all_coprime = false;            break;        }    }    return all_coprime;}Â
// Driver Codepublic static void Main(String[] args){    int []A = { 3, 5, 11, 7, 19 };    int arr_size = A.Length;         if (allCoprime(A, arr_size))     {        Console.Write("Yes");    }    else    {        Console.Write("No");    }}}Â
// This code is contributed by Amit Katiyar |
Javascript
// JS implementation of the// above approachÂ
// Function to store and// check the factorsfunction findFactor(value, factors){Â Â Â Â factors.add(value);Â Â Â Â for (var i = 2; i * i <= value; i++) {Â Â Â Â Â Â Â Â if (value % i == 0) {Â
            // Check if factors are equal            if (value == i * i) {Â
                // Check if the factor is                // already present                if (factors.has(i)) {                    return true;                }                else {Â
                    // Insert the factor in set                    factors.add(i);                }            }            else {Â
                // Check if the factor is                // already present                if (factors.has(i)                    || factors.has(Math.floor(value / i))){                    return true;                }                else {Â
                    // Insert the factors in set                    factors.add(i);                    factors.add(Math.floor(value / i));                }            }        }    }    return false;}Â
// Function to check if all the// pairs of array elements// are coprime with each otherfunction allCoprime(A, n){Â Â Â Â let all_coprime = true;Â Â Â Â let factors = new Set();Â Â Â Â for (var i = 0; i < n; i++) {Â Â Â Â Â Â Â Â if (A[i] == 1)Â Â Â Â Â Â Â Â Â Â Â Â continue;Â
        // Check if factors of A[i]        // haven't occurred previously        if (findFactor(A[i], factors)) {            all_coprime = false;            break;        }    }    return all_coprime;}Â
// Driver Codelet A = [ 3, 5, 11, 7, 19 ];let arr_size = A.lengthif (allCoprime(A, arr_size)) {Â Â Â Â console.log("Yes");}else {Â Â Â Â console.log("No");}Â
// This code is contributed by phasing17. |
Yes
Time Complexity: O(N3/2)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



