constgetPrimeFactors = (num) => { const factors = newSet(); let x = num; for (let i = 2; i * i <= x; i++) { if (x % i === 0) { factors.add(i); while (x % i === 0) x /= i; } } if (x > 1) factors.add(x); return factors; };
const primeToIndex = newMap(); for (const num of nums) { const factors = getPrimeFactors(num); for (const f of factors) { if (!primeToIndex.has(f)) { primeToIndex.set(f, num); } else { union(num, primeToIndex.get(f)); } } }
const count = newMap(); for (const num of nums) { const root = find(num); count.set(root, (count.get(root) || 0) + 1); }