📌  相关文章
📜  计算乘积包含单个不同质因子的对

📅  最后修改于: 2021-09-06 06:42:51             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是计算给定数组中的对数,其乘积仅包含一个不同的素数因子。

例子:

朴素的方法:解决这个问题的最简单的方法是遍历数组并生成数组的所有可能对,对于每一对,检查元素的乘积是否只包含一个不同的素数因子。如果发现为真,则增加计数。最后,打印计数。

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

高效的方法:优化上述方法的想法是使用哈希。请按照以下步骤解决问题:

  • 初始化一个变量,比如cntof1来存储值为1的数组元素的计数。
  • 创建映射,比如mp来存储只包含一个不同质因子的数组元素的计数。
  • 遍历数组,对于每个数组元素,检查不同质因子的计数是否为1 。如果发现为真,则将当前元素插入到 mp 中。
  • 初始化一个变量,比如res来存储其元素乘积仅包含一个不同质因子的对的计数。
  • 遍历地图并更新res += cntof1 * (X) + (X *(X- 1)) / 2 。其中 X 存储仅包含单个不同质因子i的数组元素的计数。
  • 最后,打印res的值。

下面是上述方法的实现

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
 
// Function to find a single
// distinct prime factor of N
int singlePrimeFactor(int N)
{
     
    // Stores distinct
    // prime factors of N
    unordered_set
              disPrimeFact;
   
   
    // Calculate prime factor of N
    for (int i = 2; i * i <= N; ++i) {
         
         
        // Calculate distinct
        // prime factor
        while (N % i == 0) {
             
             
            // Insert i into
            // disPrimeFact
            disPrimeFact.insert(i);
             
             
            // Update N
            N /= i;
        }
    }
    
    
    // If N is not equal to 1
    if (N != 1)
    {
         
        // Insert N into
        // disPrimeFact
        disPrimeFact.insert(N);
    }
     
     
    // If N contains a single
    // distinct prime factor
    if (disPrimeFact.size() == 1) {
         
         
        // Return single distinct
        // prime factor of N
        return *disPrimeFact.begin();
    }   
     
     
    // If N contains more than one
    // distinct prime factor   
    return -1;
}
 
 
// Function to count pairs in the array
// whose product contains only
// single distinct prime factor
int cntsingleFactorPair(int arr[], int N)
{
     
   // Stores count of 1s
   // in the array
    int countOf1 = 0;
     
     
    // mp[i]: Stores count of array elements
    // whose distinct prime factor is only i
    unordered_map mp;
     
     
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
         
         
        // If current element is 1
        if(arr[i] == 1)
        {
            countOf1++;
            continue;
        }
       
       
        // Store distinct
        // prime factor of arr[i]
        int factorValue
          = singlePrimeFactor(arr[i]);
         
         
        // If arr[i] contains more
        // than one prime factor
        if (factorValue == -1) {
            continue;
        }
         
         
        // If arr[i] contains
        // a single prime factor
        else {
            mp[factorValue]++;
        }
    }
       
       
    // Stores the count of pairs whose
    // product of elements contains only
    // a single distinct prime factor
    int res = 0;
   
   
    // Traverse the map mp[]
    for (auto it : mp) { 
         
         
        // Stores count of array elements
        // whose prime factor is (it.first)
        int X = it.second;
         
         
        // Update res
        res += countOf1 * X +
              (X * (X - 1) ) / 2;
    }
     
    return res;
}
 
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntsingleFactorPair(arr, N);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find a single
// distinct prime factor of N
static int singlePrimeFactor(int N)
{
  // Stores distinct
  // prime factors of N
  HashSet disPrimeFact =
                   new HashSet<>();
 
  // Calculate prime factor of N
  for (int i = 2;
           i * i <= N; ++i)
  {
    // Calculate distinct
    // prime factor
    while (N % i == 0)
    {
      // Insert i into
      // disPrimeFact
      disPrimeFact.add(i);
 
      // Update N
      N /= i;
    }
  }
 
  // If N is not equal to 1
  if (N != 1)
  {
    // Insert N into
    // disPrimeFact
    disPrimeFact.add(N);
  }
 
  // If N contains a single
  // distinct prime factor
  if (disPrimeFact.size() == 1)
  {
    // Return single distinct
    // prime factor of N
    for(int i : disPrimeFact)
      return i;
  }
 
  // If N contains more than
  // one distinct prime factor   
  return -1;
}
 
 
// Function to count pairs in
// the array whose product
// contains only single distinct
// prime factor
static int cntsingleFactorPair(int arr[],
                               int N)
{  
  // Stores count of 1s
  // in the array
  int countOf1 = 0;
 
  // mp[i]: Stores count of array
  // elements whose distinct prime
  // factor is only i
  HashMap mp = new HashMap();
 
  // Traverse the array arr[]
  for (int i = 0; i < N; i++)
  {
    // If current element is 1
    if(arr[i] == 1)
    {
      countOf1++;
      continue;
    }
 
    // Store distinct
    // prime factor of arr[i]
    int factorValue =
        singlePrimeFactor(arr[i]);
 
    // If arr[i] contains more
    // than one prime factor
    if (factorValue == -1)
    {
      continue;
    }
 
    // If arr[i] contains
    // a single prime factor
    else
    {
      if(mp.containsKey(factorValue))
        mp.put(factorValue,
        mp.get(factorValue) + 1);
      else
        mp.put(factorValue, 1);
    }
  }
 
  // Stores the count of pairs whose
  // product of elements contains only
  // a single distinct prime factor
  int res = 0;
 
  // Traverse the map mp[]
  for (Map.Entry it :
       mp.entrySet())
  {
    // Stores count of array
    // elements whose prime
    // factor is (it.first)
    int X = it.getValue();
 
    // Update res
    res += countOf1 * X +
           (X * (X - 1) ) / 2;
  }
 
  return res;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 3, 4};
  int N = arr.length;
  System.out.print(
         cntsingleFactorPair(arr, N));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Function to find a single
# distinct prime factor of N
def singlePrimeFactor(N):
     
    # Stores distinct
    # prime factors of N
    disPrimeFact = {}
     
    # Calculate prime factor of N
    for i in range(2, N + 1):
        if i * i > N:
            break
         
        # Calculate distinct
        # prime factor
        while (N % i == 0):
             
            # Insert i into
            # disPrimeFact
            disPrimeFact[i] = 1
             
            # Update N
            N //= i
 
    # If N is not equal to 1
    if (N != 1):
         
        # Insert N into
        # disPrimeFact
        disPrimeFact[N] = 1
         
    # If N contains a single
    # distinct prime factor
    if (len(disPrimeFact) == 1):
         
        # Return single distinct
        # prime factor of N
        return list(disPrimeFact.keys())[0]
         
    # If N contains more than one
    # distinct prime factor
    return -1
 
# Function to count pairs in the array
# whose product contains only
# single distinct prime factor
def cntsingleFactorPair(arr, N):
     
    # Stores count of 1s
    # in the array
    countOf1 = 0
 
    # mp[i]: Stores count of array elements
    # whose distinct prime factor is only i
    mp = {}
 
    # Traverse the array arr[]
    for i in range(N):
         
        # If current element is 1
        if (arr[i] == 1):
            countOf1 += 1
            continue
 
        # Store distinct
        # prime factor of arr[i]
        factorValue = singlePrimeFactor(arr[i])
 
        # If arr[i] contains more
        # than one prime factor
        if (factorValue == -1):
            continue
         
        # If arr[i] contains
        # a single prime factor
        else:
            mp[factorValue] = mp.get(factorValue, 0) + 1
 
    # Stores the count of pairs whose
    # product of elements contains only
    # a single distinct prime factor
    res = 0
 
    # Traverse the map mp[]
    for it in mp:
         
        # Stores count of array elements
        # whose prime factor is (it.first)
        X = mp[it]
 
        # Update res
        res += countOf1 * X + (X * (X - 1) ) // 2
 
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 4 ]
    N = len(arr)
     
    print(cntsingleFactorPair(arr, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find a single
// distinct prime factor of N
static int singlePrimeFactor(int N)
{
  // Stores distinct
  // prime factors of N
  HashSet disPrimeFact =
          new HashSet();
 
  // Calculate prime factor of N
  for (int i = 2;
           i * i <= N; ++i)
  {
    // Calculate distinct
    // prime factor
    while (N % i == 0)
    {
      // Insert i into
      // disPrimeFact
      disPrimeFact.Add(i);
 
      // Update N
      N /= i;
    }
  }
 
  // If N is not equal to 1
  if(N != 1)
  {
    // Insert N into
    // disPrimeFact
    disPrimeFact.Add(N);
  }
 
  // If N contains a single
  // distinct prime factor
  if (disPrimeFact.Count == 1)
  {
    // Return single distinct
    // prime factor of N
    foreach(int i in disPrimeFact)
      return i;
  }
 
  // If N contains more than
  // one distinct prime factor   
  return -1;
}
 
 
// Function to count pairs in
// the array whose product
// contains only single distinct
// prime factor
static int cntsingleFactorPair(int []arr,
                               int N)
{  
  // Stores count of 1s
  // in the array
  int countOf1 = 0;
 
  // mp[i]: Stores count of array
  // elements whose distinct prime
  // factor is only i
  Dictionary mp =
             new Dictionary();
 
  // Traverse the array arr[]
  for (int i = 0; i < N; i++)
  {
    // If current element is 1
    if(arr[i] == 1)
    {
      countOf1++;
      continue;
    }
 
    // Store distinct
    // prime factor of arr[i]
    int factorValue =
        singlePrimeFactor(arr[i]);
 
    // If arr[i] contains more
    // than one prime factor
    if (factorValue == -1)
    {
      continue;
    }
 
    // If arr[i] contains
    // a single prime factor
    else
    {
      if(mp.ContainsKey(factorValue))
        mp[factorValue] = mp[factorValue] + 1;
      else
        mp.Add(factorValue, 1);
    }
  }
 
  // Stores the count of pairs whose
  // product of elements contains only
  // a single distinct prime factor
  int res = 0;
 
  // Traverse the map mp[]
  foreach(KeyValuePair ele1 in mp)
  {
    // Stores count of array
    // elements whose prime
    // factor is (it.first)
    int X = ele1.Value;
 
    // Update res
    res += countOf1 * X +
           (X * (X - 1) ) / 2;
  }
 
  return res;
}
 
// Driver Code
public static void Main()
{
  int []arr = {1, 2, 3, 4};
  int N = arr.Length;
  Console.WriteLine(
         cntsingleFactorPair(arr, N));
}
}
 
// This code is contributed by bgangwar59


输出:
4









时间复杂度: O(N√X) ,其中X是给定数组的最大元素。
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live