File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments