Skip to content

Commit f238753

Browse files
authored
Create count-array-pairs-divisible-by-k.cpp
1 parent d409c43 commit f238753

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(nlogk + sqrt(k)^2) = O(nlogk + k)
2+
// Space: O(sqrt(k)), number of factors of k is at most sqrt(k)
3+
4+
// math, number theory
5+
class Solution {
6+
public:
7+
long long countPairs(vector<int>& nums, int k) {
8+
unordered_map<int64_t, int64_t> cnt;
9+
for (const auto& x : nums) {
10+
++cnt[gcd(x, k)];
11+
}
12+
int64_t result = 0;
13+
for (const auto& [x, c1] : cnt) {
14+
for (const auto& [y, c2] : cnt) {
15+
if (x > y || x * y % k) {
16+
continue;
17+
}
18+
result += (x != y) ? c1 * c2 : c1 * (c1 - 1) / 2;
19+
}
20+
}
21+
return result;
22+
}
23+
};
24+
25+
// Time: O(nlogk + n * sqrt(k))
26+
// Space: O(sqrt(k)), number of factors of k is at most sqrt(k)
27+
// math, number theory
28+
class Solution2 {
29+
public:
30+
long long countPairs(vector<int>& nums, int k) {
31+
int64_t result = 0;
32+
unordered_map<int64_t, int64_t> gcds;
33+
for (const auto& i : nums) {
34+
const int gcd_i = gcd(i, k);
35+
for (const auto& [gcd_j, cnt] : gcds) {
36+
if (gcd_i * gcd_j % k == 0) {
37+
result += cnt;
38+
}
39+
}
40+
++gcds[gcd_i];
41+
}
42+
return result;
43+
}
44+
};

0 commit comments

Comments
 (0)