📌  相关文章
📜  计算乘积为合数的数组中的对

📅  最后修改于: 2021-10-26 05:10:39             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是计算给定数组中乘积为合数的所有对。

例子:

天真的方法:这个想法是遍历数组并生成给定数组的所有可能对。对于每一对,检查其元素的乘积是否为合数。如果发现为真,则将计数加 1。 按照以下步骤解决问题:

  • 初始化一个变量,比如res来存储乘积为合数的对的计数。
  • 遍历数组并生成给定数组的所有可能对。
  • 对于每一对,检查他们的产品是否是复合的。如果发现为真,则将res的值增加1
  • 最后,打印res的值。

下面是上述方法的实现

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check if a
// number is prime or not
bool isComposite(int N)
{
    // Check if N is multiple
    // of i or not.
    for (int i = 2; i * i <= N;
         i++) {
 
        // If N is multiple of i.
        if (N % i == 0) {
            return true;
        }
    }
 
    return false;
}
 
// Function to get the count
// of pairs whose product
// is a composite number.
int compositePair(int arr[], int N)
{
    // Stores the count of pairs
    // whose product is
    // a composite number
    int res = 0;
 
    // Generate all possible pairs
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N;
             j++) {
 
            // Stores the product of
            // element of current pair
            int prod = arr[i] * arr[j];
 
            // If prod is a
            // composite number
            if (isComposite(prod)) {
                res++;
            }
        }
    }
    return res;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 1, 2, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << compositePair(arr, N);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.io.*;
class GFG{
     
// Function to check if a
// number is prime or not
static boolean isComposite(int N)
{
  // Check if N is multiple
  // of i or not.
  for (int i = 2; i * i <= N; i++)
  {
    // If N is multiple of i.
    if (N % i == 0)
    {
      return true;
    }
  }
  return false;
}
  
// Function to get the count
// of pairs whose product
// is a composite number.
static int compositePair(int arr[],
                         int N)
{
  // Stores the count of pairs
  // whose product is
  // a composite number
  int res = 0;
 
  // Generate all possible pairs
  for (int i = 0; i < N; i++)
  {
    for (int j = i + 1; j < N; j++)
    {
      // Stores the product of
      // element of current pair
      int prod = arr[i] * arr[j];
 
      // If prod is a
      // composite number
      if (isComposite(prod))
      {
        res++;
      }
    }
  }
  return res;
}
  
// Driver Code
public static void main (String[] args)
{
  int arr[] = {1, 1, 2, 2, 8};
  int N = arr.length;
  System.out.println(compositePair(arr, N));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program to implement
# the above approach
 
# Function to check if a
# number is prime or not
def isComposite(N):
     
    # Check if N is multiple
    # of i or not.
    for i in range(2, N + 1):
        if i * i > N:
            break
 
        # If N is multiple of i.
        if (N % i == 0):
            return True
 
    return False
     
# Function to get the count
# of pairs whose product
# is a composite number.
def compositePair(arr, N):
     
    # Stores the count of pairs
    # whose product is
    # a composite number
    res = 0
 
    # Generate all possible pairs
    for i in range(N):
        for j in range(i + 1, N):
 
            # Stores the product of
            # element of current pair
            prod = arr[i] * arr[j]
 
            # If prod is a
            # composite number
            if (isComposite(prod)):
                res += 1
                 
    return res
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 1, 1, 2, 2, 8 ]
    N = len(arr)
     
    print(compositePair(arr, N))
 
# This code is contributed by mohit kumar 29


C#
// C# Program to implement
// the above approach
using System;
class GFG{
     
// Function to check if a
// number is prime or not
static bool isComposite(int N)
{
  // Check if N is multiple
  // of i or not.
  for (int i = 2; i * i <= N; i++)
  {
    // If N is multiple of i.
    if (N % i == 0)
    {
      return true;
    }
  }
  return false;
}
  
// Function to get the count
// of pairs whose product
// is a composite number.
static int compositePair(int []arr,
                         int N)
{
  // Stores the count of pairs
  // whose product is
  // a composite number
  int res = 0;
 
  // Generate all possible pairs
  for (int i = 0; i < N; i++)
  {
    for (int j = i + 1; j < N; j++)
    {
      // Stores the product of
      // element of current pair
      int prod = arr[i] * arr[j];
 
      // If prod is a
      // composite number
      if (isComposite(prod))
      {
        res++;
      }
    }
  }
  return res;
}
  
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 1, 2, 2, 8};
  int N = arr.Length;
  Console.WriteLine(compositePair(arr, N));
}
}
 
// This code is contributed by shikhasingrajput


Javascript


C++
// C++ program to implement
// the above approach
#include 
using namespace std;
#define X 1000000
 
// Function to get all
// the prime numbers in
// the range[1, X]
vector getPrimeNum()
{
    // Stores the boolean value
    // to check if a number is
    // prime or not
    vector isPrime(X, true);
 
    isPrime[0] = false;
    isPrime[1] = false;
 
    // Mark all non prime
    // numbers as false
    for (int i = 2; i * i <= X;
         i++) {
 
        // If i is prime number
        if (isPrime[i] == true) {
            for (int j = i * i;
                 j < X; j += i) {
 
                // Mark j as
                // a composite number
                isPrime[j] = false;
            }
        }
    }
    return isPrime;
}
 
// Function to get the count of pairs
// whose product is a composite number
int cntPairs(int arr[], int N)
{
    // Stores the boolean value
    // to check if a number is
    // prime or not
    vector isPrime
        = getPrimeNum();
 
    // Stores the count of 1s
    int cntOne = 0;
 
    // Stores the count
    // of prime numbers
    int cntPrime = 0;
 
    // Traverse the given array.
    for (int i = 0; i < N; i++) {
        if (arr[i] == 1) {
            cntOne += 1;
        }
        else if (isPrime[i]) {
            cntPrime += 1;
        }
    }
 
    // Stores count of pairs whose
    // product is not a composite number
    int cntNonComp = 0;
    cntNonComp = cntPrime * cntOne
                 + cntOne * (cntOne - 1) / 2;
 
    // Stores the count of pairs
    // whose product is composite number
    int res = 0;
    res = N * (N - 1) / 2 - cntNonComp;
 
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 2, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntPairs(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
public static int X = 1000000;
 
// Function to get all
// the prime numbers in
// the range[1, X]
public static boolean[] getPrimeNum()
{
     
    // Stores the boolean value
    // to check if a number is
    // prime or not
    boolean isPrime[] = new boolean[X];
    Arrays.fill(isPrime, true);
  
    isPrime[0] = false;
    isPrime[1] = false;
  
    // Mark all non prime
    // numbers as false
    for(int i = 2; i * i <= X; i++)
    {
         
        // If i is prime number
        if (isPrime[i] == true)
        {
            for(int j = i * i; j < X; j += i)
            {
                 
                // Mark j as a composite
                // number
                isPrime[j] = false;
            }
        }
    }
    return isPrime;
}
  
// Function to get the count of pairs
// whose product is a composite number
public static int cntPairs(int arr[], int N)
{
     
    // Stores the boolean value
    // to check if a number is
    // prime or not
    boolean isPrime[] = getPrimeNum();
  
    // Stores the count of 1s
    int cntOne = 0;
  
    // Stores the count
    // of prime numbers
    int cntPrime = 0;
  
    // Traverse the given array.
    for(int i = 0; i < N; i++)
    {
        if (arr[i] == 1)
        {
            cntOne += 1;
        }
        else if (isPrime[i])
        {
            cntPrime += 1;
        }
    }
  
    // Stores count of pairs whose
    // product is not a composite number
    int cntNonComp = 0;
    cntNonComp = cntPrime * cntOne +
                   cntOne * (cntOne - 1) / 2;
  
    // Stores the count of pairs
    // whose product is composite number
    int res = 0;
    res = N * (N - 1) / 2 - cntNonComp;
  
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 1, 2, 2, 8 };
    int N = arr.length;
     
    System.out.println(cntPairs(arr, N));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to implement
# the above approach
X = 1000000
 
# Function to get all
# the prime numbers in
# the range[1, X]
def getPrimeNum():
 
    # Stores the boolean value
    # to check if a number is
    # prime or not
    isPrime = [True] * (X)
 
    isPrime[0] = False
    isPrime[1] = False
 
    # Mark all non prime
    # numbers as false
    i = 2
    while i * i <= X:
 
        # If i is prime number
        if (isPrime[i] == True):
            for j in range(i * i,
                           X, i):
 
                # Mark j as
                # a composite number
                isPrime[j] = False
 
        i += 1
 
    return isPrime
 
# Function to get the count
# of pairs whose product
# is a composite number
def cntPairs(arr, N):
 
    # Stores the boolean value
    # to check if a number is
    # prime or not
    isPrime = getPrimeNum()
 
    # Stores the count of 1s
    cntOne = 0
 
    # Stores the count
    # of prime numbers
    cntPrime = 0
 
    # Traverse the given array.
    for i in range(N):
        if (arr[i] == 1):
            cntOne += 1
        elif (isPrime[i]):
            cntPrime += 1
 
    # Stores count of pairs whose
    # product is not a composite number
    cntNonComp = 0
    cntNonComp = (cntPrime * cntOne +
                  cntOne * (cntOne - 1) // 2)
 
    # Stores the count of pairs
    # whose product is composite number
    res = 0
    res = (N * (N - 1) // 2 -
           cntNonComp)
 
    return res
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 1, 2, 2, 8]
    N = len(arr)
    print(cntPairs(arr, N))
 
# This code is contributed by Chitranayal


C#
// C# program to implement
// the above approach
using System;
class GFG{
     
public static int X = 1000000;
 
// Function to get all
// the prime numbers in
// the range[1, X]
public static bool[] getPrimeNum()
{
  // Stores the bool value
  // to check if a number is
  // prime or not
  bool []isPrime = new bool[X];
   
  for(int i = 0; i < X; i++)
    isPrime[i] = true;
 
  isPrime[0] = false;
  isPrime[1] = false;
 
  // Mark all non prime
  // numbers as false
  for(int i = 2;
          i * i <= X; i++)
  {
    // If i is prime number
    if (isPrime[i] == true)
    {
      for(int j = i * i;
              j < X; j += i)
      {
        // Mark j as a composite
        // number
        isPrime[j] = false;
      }
    }
  }
  return isPrime;
}
  
// Function to get the count of pairs
// whose product is a composite number
public static int cntPairs(int []arr,
                           int N)
{   
  // Stores the bool value
  // to check if a number is
  // prime or not
  bool []isPrime = getPrimeNum();
 
  // Stores the count of 1s
  int cntOne = 0;
 
  // Stores the count
  // of prime numbers
  int cntPrime = 0;
 
  // Traverse the given array.
  for(int i = 0; i < N; i++)
  {
    if (arr[i] == 1)
    {
      cntOne += 1;
    }
    else if (isPrime[i])
    {
      cntPrime += 1;
    }
  }
 
  // Stores count of pairs
  // whose product is not
  // a composite number
  int cntNonComp = 0;
  cntNonComp = cntPrime * cntOne +
               cntOne * (cntOne - 1) / 2;
 
  // Stores the count of pairs
  // whose product is composite number
  int res = 0;
  res = N * (N - 1) / 2 - cntNonComp;
 
  return res;
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {1, 1, 2, 2, 8};
  int N = arr.Length;
  Console.WriteLine(cntPairs(arr, N));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出
5

时间复杂度: O(N 2 √X),其中 X 是给定数组中一对的最大可能乘积。
辅助空间: O(1)

高效方法:为了优化上述方法,其思想是利用所有质数和 1 都不是合数的事实。请按照以下步骤解决问题:

  • 初始化两个变量cntPrimecntOne以分别存储给定数组中1和素数的计数。
  • 初始化一个变量,比如res来存储乘积为合数的对的计数。
  • 乘积不是合数的总对数为:
  • 因此,乘积为合数的对的总数为:
  • 最后,打印res的值。

下面是上述方法的实现

C++

// C++ program to implement
// the above approach
#include 
using namespace std;
#define X 1000000
 
// Function to get all
// the prime numbers in
// the range[1, X]
vector getPrimeNum()
{
    // Stores the boolean value
    // to check if a number is
    // prime or not
    vector isPrime(X, true);
 
    isPrime[0] = false;
    isPrime[1] = false;
 
    // Mark all non prime
    // numbers as false
    for (int i = 2; i * i <= X;
         i++) {
 
        // If i is prime number
        if (isPrime[i] == true) {
            for (int j = i * i;
                 j < X; j += i) {
 
                // Mark j as
                // a composite number
                isPrime[j] = false;
            }
        }
    }
    return isPrime;
}
 
// Function to get the count of pairs
// whose product is a composite number
int cntPairs(int arr[], int N)
{
    // Stores the boolean value
    // to check if a number is
    // prime or not
    vector isPrime
        = getPrimeNum();
 
    // Stores the count of 1s
    int cntOne = 0;
 
    // Stores the count
    // of prime numbers
    int cntPrime = 0;
 
    // Traverse the given array.
    for (int i = 0; i < N; i++) {
        if (arr[i] == 1) {
            cntOne += 1;
        }
        else if (isPrime[i]) {
            cntPrime += 1;
        }
    }
 
    // Stores count of pairs whose
    // product is not a composite number
    int cntNonComp = 0;
    cntNonComp = cntPrime * cntOne
                 + cntOne * (cntOne - 1) / 2;
 
    // Stores the count of pairs
    // whose product is composite number
    int res = 0;
    res = N * (N - 1) / 2 - cntNonComp;
 
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 2, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntPairs(arr, N);
}

Java

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
public static int X = 1000000;
 
// Function to get all
// the prime numbers in
// the range[1, X]
public static boolean[] getPrimeNum()
{
     
    // Stores the boolean value
    // to check if a number is
    // prime or not
    boolean isPrime[] = new boolean[X];
    Arrays.fill(isPrime, true);
  
    isPrime[0] = false;
    isPrime[1] = false;
  
    // Mark all non prime
    // numbers as false
    for(int i = 2; i * i <= X; i++)
    {
         
        // If i is prime number
        if (isPrime[i] == true)
        {
            for(int j = i * i; j < X; j += i)
            {
                 
                // Mark j as a composite
                // number
                isPrime[j] = false;
            }
        }
    }
    return isPrime;
}
  
// Function to get the count of pairs
// whose product is a composite number
public static int cntPairs(int arr[], int N)
{
     
    // Stores the boolean value
    // to check if a number is
    // prime or not
    boolean isPrime[] = getPrimeNum();
  
    // Stores the count of 1s
    int cntOne = 0;
  
    // Stores the count
    // of prime numbers
    int cntPrime = 0;
  
    // Traverse the given array.
    for(int i = 0; i < N; i++)
    {
        if (arr[i] == 1)
        {
            cntOne += 1;
        }
        else if (isPrime[i])
        {
            cntPrime += 1;
        }
    }
  
    // Stores count of pairs whose
    // product is not a composite number
    int cntNonComp = 0;
    cntNonComp = cntPrime * cntOne +
                   cntOne * (cntOne - 1) / 2;
  
    // Stores the count of pairs
    // whose product is composite number
    int res = 0;
    res = N * (N - 1) / 2 - cntNonComp;
  
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 1, 2, 2, 8 };
    int N = arr.length;
     
    System.out.println(cntPairs(arr, N));
}
}
 
// This code is contributed by divyeshrabadiya07

蟒蛇3

# Python3 program to implement
# the above approach
X = 1000000
 
# Function to get all
# the prime numbers in
# the range[1, X]
def getPrimeNum():
 
    # Stores the boolean value
    # to check if a number is
    # prime or not
    isPrime = [True] * (X)
 
    isPrime[0] = False
    isPrime[1] = False
 
    # Mark all non prime
    # numbers as false
    i = 2
    while i * i <= X:
 
        # If i is prime number
        if (isPrime[i] == True):
            for j in range(i * i,
                           X, i):
 
                # Mark j as
                # a composite number
                isPrime[j] = False
 
        i += 1
 
    return isPrime
 
# Function to get the count
# of pairs whose product
# is a composite number
def cntPairs(arr, N):
 
    # Stores the boolean value
    # to check if a number is
    # prime or not
    isPrime = getPrimeNum()
 
    # Stores the count of 1s
    cntOne = 0
 
    # Stores the count
    # of prime numbers
    cntPrime = 0
 
    # Traverse the given array.
    for i in range(N):
        if (arr[i] == 1):
            cntOne += 1
        elif (isPrime[i]):
            cntPrime += 1
 
    # Stores count of pairs whose
    # product is not a composite number
    cntNonComp = 0
    cntNonComp = (cntPrime * cntOne +
                  cntOne * (cntOne - 1) // 2)
 
    # Stores the count of pairs
    # whose product is composite number
    res = 0
    res = (N * (N - 1) // 2 -
           cntNonComp)
 
    return res
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 1, 2, 2, 8]
    N = len(arr)
    print(cntPairs(arr, N))
 
# This code is contributed by Chitranayal

C#

// C# program to implement
// the above approach
using System;
class GFG{
     
public static int X = 1000000;
 
// Function to get all
// the prime numbers in
// the range[1, X]
public static bool[] getPrimeNum()
{
  // Stores the bool value
  // to check if a number is
  // prime or not
  bool []isPrime = new bool[X];
   
  for(int i = 0; i < X; i++)
    isPrime[i] = true;
 
  isPrime[0] = false;
  isPrime[1] = false;
 
  // Mark all non prime
  // numbers as false
  for(int i = 2;
          i * i <= X; i++)
  {
    // If i is prime number
    if (isPrime[i] == true)
    {
      for(int j = i * i;
              j < X; j += i)
      {
        // Mark j as a composite
        // number
        isPrime[j] = false;
      }
    }
  }
  return isPrime;
}
  
// Function to get the count of pairs
// whose product is a composite number
public static int cntPairs(int []arr,
                           int N)
{   
  // Stores the bool value
  // to check if a number is
  // prime or not
  bool []isPrime = getPrimeNum();
 
  // Stores the count of 1s
  int cntOne = 0;
 
  // Stores the count
  // of prime numbers
  int cntPrime = 0;
 
  // Traverse the given array.
  for(int i = 0; i < N; i++)
  {
    if (arr[i] == 1)
    {
      cntOne += 1;
    }
    else if (isPrime[i])
    {
      cntPrime += 1;
    }
  }
 
  // Stores count of pairs
  // whose product is not
  // a composite number
  int cntNonComp = 0;
  cntNonComp = cntPrime * cntOne +
               cntOne * (cntOne - 1) / 2;
 
  // Stores the count of pairs
  // whose product is composite number
  int res = 0;
  res = N * (N - 1) / 2 - cntNonComp;
 
  return res;
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {1, 1, 2, 2, 8};
  int N = arr.Length;
  Console.WriteLine(cntPairs(arr, N));
}
}
 
// This code is contributed by gauravrajput1

Javascript


输出
5

时间复杂度: O(N + X × log(log(X))),其中 X 存储给定数组中一对的最大可能乘积。
辅助空间: O(X)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程