Skip to content

2183. Count Array Pairs Divisible by K 👍

  • Time: $O(n\sqrt{k})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  long long countPairs(vector<int>& nums, int k) {
    long ans = 0;
    unordered_map<int, int> gcds;

    for (const int num : nums) {
      const int gcd_i = gcd(num, k);
      for (const auto& [gcd_j, count] : gcds)
        if (static_cast<long>(gcd_i) * gcd_j % k == 0)
          ans += count;
      ++gcds[gcd_i];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long countPairs(int[] nums, int k) {
    long ans = 0;
    Map<Integer, Integer> gcds = new HashMap<>();

    for (final int num : nums) {
      final int gcd_i = gcd(num, k);
      for (final int gcd_j : gcds.keySet())
        if ((long) gcd_i * gcd_j % k == 0)
          ans += gcds.get(gcd_j);
      gcds.merge(gcd_i, 1, Integer::sum);
    }

    return ans;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def countPairs(self, nums: list[int], k: int) -> int:
    ans = 0
    gcds = collections.Counter()

    for num in nums:
      gcd_i = math.gcd(num, k)
      for gcd_j, count in gcds.items():
        if gcd_i * gcd_j % k == 0:
          ans += count
      gcds[gcd_i] += 1

    return ans