Skip to content

Commit 8c0ff0c

Browse files
authored
Update 1994-the-number-of-good-subsets.js
1 parent bb76d23 commit 8c0ff0c

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

1994-the-number-of-good-subsets.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,89 @@
1+
const M = 1e9 + 7
2+
3+
/**
4+
* @param {number[]} nums
5+
* @return {number}
6+
*/
7+
const numberOfGoodSubsets = function (nums) {
8+
const set = new Set([
9+
2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30,
10+
])
11+
const map = new Map()
12+
let count1 = 0
13+
14+
for (const x of nums) {
15+
if (set.has(x)) {
16+
map.set(x, (map.get(x) || 0) + 1)
17+
}
18+
if (x === 1) {
19+
count1++
20+
}
21+
}
22+
23+
const n = map.size
24+
const count = []
25+
const digit = []
26+
for (const [key, value] of map) {
27+
digit.push(key)
28+
count.push(value)
29+
}
30+
31+
let ret = 0
32+
for (let state = 1; state < 1 << n; state++) {
33+
let flag = 1
34+
for (let i = 0; i < n; i++) {
35+
if (((state >> i) & 1) === 0) continue
36+
for (let j = i + 1; j < n; j++) {
37+
if (((state >> j) & 1) === 0) continue
38+
if (gcd(digit[i], digit[j]) !== 1) {
39+
flag = 0
40+
break
41+
}
42+
}
43+
if (flag === 0) break
44+
}
45+
46+
if (flag === 0) continue
47+
48+
let ans = 1
49+
for (let i = 0; i < n; i++) {
50+
if (((state >> i) & 1) === 0) continue
51+
ans = mul(ans, count[i])
52+
}
53+
ret = (ret + ans) % M
54+
}
55+
56+
ret = mul(ret, quickMul(2, count1))
57+
return ret
58+
}
59+
60+
function quickMul(x, N) {
61+
if (N === 0) {
62+
return 1
63+
}
64+
const y = quickMul(x, Math.floor(N / 2))
65+
return N % 2 === 0 ? mul(y, y) : mul(y, y, x)
66+
}
67+
68+
function mul(...arr) {
69+
let res = 1n
70+
for (const e of arr) {
71+
res *= BigInt(e)
72+
}
73+
74+
return Number(res % BigInt(M))
75+
}
76+
77+
function gcd(a, b) {
78+
while (b) {
79+
;[a, b] = [b, a % b]
80+
}
81+
return a
82+
}
83+
84+
// another
85+
86+
187
/**
288
* @param {number[]} nums
389
* @return {number}

0 commit comments

Comments
 (0)