📌  相关文章
📜  Array 中乘积可被 K 整除的对数

📅  最后修改于: 2022-05-13 01:56:06.559000             🧑  作者: Mango

Array 中乘积可被 K 整除的对数

给定一个数组A[]和正整数K ,任务是计算数组中其乘积可被K整除的对的总数。

例子 :

天真的方法:为了找到所有对的计数,我们可以简单地进行嵌套循环迭代,并且对于每个元素,我们可以检查所有剩余元素的乘积是否可以被给定键整除。

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

高效方法:基于以下观察,可以使用散列有效地解决问题:

请按照以下步骤解决问题:

  • 创建一个将GCD(A[i], K)存储为并将其出现作为值的映射。
  • 对于数组的每个元素,检查map的所有元素,map的元素是否能被X整除(X = K除以GCD时的商(A[i], K)
    •  如果是,则将该元素的出现从地图添加到答案。
    • 此外,使用key不断增加每个元素的GCD的出现次数。
  • 返回最终计数。

下面是上述方法的实现

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Program to count pairs whose product
// is divisible by key
long long countPairs(vector& A, int
                                         key)
{
    long long ans = 0;
    unordered_map mp;
 
    for (auto ele : A) {
        // Calculate gcd of nums[i] and
        // key
        long long gcd = __gcd(key, ele);
        long long x = key / gcd;
 
        // Iterate over all possible gcds
        for (auto it : mp)
            if (it.first % x == 0)
                // Add count to answer
                ans += it.second;
        // Add gcd to map
        mp[gcd]++;
    }
 
    return ans;
}
 
// Driver code
int main()
{
    vector A = { 1, 2, 3, 4, 5 };
    int key = 2;
 
    cout << countPairs(A, key) << endl;
    return 0;
}


Java
// JAVA program for the above approach
import java.util.*;
class GFG {
 
  public static int agcd(int a, int b)
  {
    if (b == 0)
      return a;
    return agcd(b, a % b);
  }
 
  // Program to count pairs whose product
  // is divisible by key
  public static long countPairs(int[] A, int key)
  {
    long ans = 0;
    HashMap mp = new HashMap<>();
 
    for (int i = 0; i < A.length; ++i)
    {
 
      // Calculate gcd of nums[i] and
      // key
      long gcd = agcd(key, A[i]);
      long x = key / gcd;
 
      // Iterate over all possible gcds
      for (Map.Entry it :
           mp.entrySet())
        if (it.getKey() % x == 0)
          // Add count to answer
          ans += it.getValue();
      // Add gcd to map
      if (mp.containsKey(gcd)) {
        mp.put(gcd, mp.get(gcd) + 1);
      }
      else {
        mp.put(gcd, 1);
      }
      // mp[gcd]++;
    }
 
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int A[] = new int[] { 1, 2, 3, 4, 5 };
    int key = 2;
 
    System.out.println(countPairs(A, key));
  }
}
 
// This code is contributed by Taranpreet


Python3
# Python3 Program to count pairs whose product
# is divisible by key
import math
 
def countPairs(A,key):
    ans = 0
    mp = {}
 
    for ele in A:
 
        # Calculate gcd of nums[i] and
        # key
        gcd = math.gcd(ele, key)
        x = key // gcd
 
        # Iterate over all possible gcds
        for Key,value in mp.items():
            if (Key % x == 0):
                # Add count to answer
                ans += value
        # Add gcd to map
        if(gcd in mp):
            mp[gcd] = mp[gcd] + 1
        else:
            mp[gcd] = 1
 
    return ans
 
# Driver code
 
A = [ 1, 2, 3, 4, 5 ]
key = 2
 
print(countPairs(A, key))
 
# This code is contrbuted by shinjanpatra


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  static int agcd(int a, int b)
  {
    if (b == 0)
      return a;
    return agcd(b, a % b);
  }
 
  // Program to count pairs whose product
  // is divisible by key
  static long countPairs(int[] A, int key)
  {
    long ans = 0;
    Dictionary mp
      = new Dictionary();
 
    for (int i = 0; i < A.Length; ++i) {
 
      // Calculate gcd of nums[i] and
      // key
      long gcd = agcd(key, A[i]);
      long x = key / gcd;
 
      // Iterate over all possible gcds
      foreach(KeyValuePair it in mp)
      {
 
        if (it.Key % x == 0)
          // Add count to answer
          ans += it.Value;
      }
      // Add gcd to map
      if (mp.ContainsKey(gcd)) {
        mp[gcd] = mp[gcd] + 1;
      }
      else {
        mp.Add(gcd, 1);
      }
      // mp[gcd]++;
    }
 
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    int[] A = { 1, 2, 3, 4, 5 };
    int key = 2;
 
    Console.WriteLine(countPairs(A, key));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
7

时间复杂度: O(N*K 1/2 )
空间复杂度: O(K 1/2 )