1454. Coprime Pair Census
A lab labels n sample vials with the positive integers in nums. Two vials are "compatible" when their labels share no prime factor, that is, when the greatest common divisor of the two labels is exactly 1. Vials are told apart by position, so two vials with equal labels are different vials, and a pair is a choice of positions i < j.
Return, as a long, the number of compatible pairs. Checking every pair is too slow; let V be the largest label and aim for O(n + V log V) time and O(V) space by counting the multiples of every divisor and combining the counts with the Moebius function.
Example 1
- Input:
- nums = [2,3,4,9]
- Output:
- 4
- Explanation:
- The coprime pairs are (2,3), (2,9), (3,4) and (4,9), giving 4.
Example 2
- Input:
- nums = [6,10,15]
- Output:
- 0
- Explanation:
- Every pair among 6, 10 and 15 shares a prime factor, so the count is 0.
Example 3
- Input:
- nums = [1,1,1]
- Output:
- 3
- Explanation:
- Each of the three pairs of ones has gcd 1, so the count is 3.
Constraints
2 ≤ n = nums.length ≤ 105
1 ≤ nums[i] ≤ 2 * 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n + V log V)
- Space
- O(V)