📜  检查数组的所有对是否互质

📅  最后修改于: 2021-04-28 17:25:18             🧑  作者: Mango

给定一个数组arr [] ,任务是检查数组的所有对是否互质互素。当每对(i,j)的GCD(arr [i],arr [j])= 1时,数组的所有对都是互质的,因此1≤i

例子:

天真的方法:一个简单的解决方案是遍历给定数组中的每对(A [i],A [j])并检查gcd (A [i],A [j])是否为1 。因此,将两者均除的唯一正整数(因子)为1。

下面是幼稚方法的实现:

C++
// C++ implementation of the
// above approach
 
#include 
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


C++
// C++ implementation of the
// above approach
 
#include 
using namespace std;
 
// Function to store and
// check the factors
bool findFactor(int value,
                unordered_set& 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 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 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 factors =
          new HashSet();
  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 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 factors = new HashSet();
     
    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


输出:
Yes




时间复杂度: O(N 2 logN)
辅助空间: O(1)

高效方法:该问题的主要观察结果是,如果仅将两个数字相除的正整数(因子)为1,则两个数字被认为是互质的。因此,我们可以将数组中每个元素的因数存储在包含此元素的容器(集合,数组等),并检查此因素是否已经存在。

插图:

下面是上述方法的实现:

C++

// C++ implementation of the
// above approach
 
#include 
using namespace std;
 
// Function to store and
// check the factors
bool findFactor(int value,
                unordered_set& 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 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 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 factors =
          new HashSet();
  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 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 factors = new HashSet();
     
    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
输出:
Yes




时间复杂度: O(N 3/2 )
辅助空间: O(N)