Skip to content
Related Articles

Related Articles

Check if all the pairs of an array are coprime with each other
  • Last Updated : 15 Oct, 2020

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 not
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;
}
 
// Driver Code
int 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 number
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
 
// Driver Code
public 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 approach
def 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 not
def 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 number
static int gcd(int a, int b)
{
  if (b == 0)
    return a;
 
  return gcd(b, a % b);
}
 
// Driver Code
public 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
Output: 
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 factors
bool 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 other
bool 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 Code
int 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.*;
class GFG{
 
// Function to store and
// check the factors
static 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 other
static 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 Code
public 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 factors
def 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 other
def 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 code
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 divyeshrabadiya07

C#




// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to store and
// check the factors
static 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 other
static 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 Code
public 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
Output: 
Yes




Time Complexity: O(N3/2)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :