Problem
You are given an integer array nums
.
Your task is to find the number of pairs of non-empty subsequences (seq1, seq2)
of nums
that satisfy the following conditions:
- The subsequences
seq1
andseq2
are disjoint , meaning no index ofnums
is common between them. - The GCD of the elements of
seq1
is equal to the GCD of the elements ofseq2
.
Return the total number of such pairs.
Since the answer may be very large, return it modulo 10^9 + 7
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 200
1 <= nums[i] <= 200
Solution
Method 1 – Inclusion-Exclusion with GCD Counting
Intuition
For each possible GCD value, count the number of subsequences whose GCD is exactly that value. For each such group, the number of ways to pick two disjoint non-empty subsequences is (2^cnt - 1)^2 - (2^{cnt} - 1), where cnt is the number of elements divisible by the GCD. We use inclusion-exclusion to avoid overcounting subsequences with GCDs that are multiples of the current value.
Approach
- Count the frequency of each number in nums.
- For each possible GCD g from max(nums) down to 1:
- Count how many numbers in nums are divisible by g (call this cnt).
- The total number of non-empty subsequences of these cnt numbers is 2^cnt - 1.
- Use inclusion-exclusion: subtract the counts for all multiples of g greater than g.
- Store the number of subsequences with GCD exactly g.
- For each g, the number of valid pairs is f[g] * (f[g] - 1), where f[g] is the number of non-empty subsequences with GCD g.
- Sum over all g and return the result modulo 1e9+7.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N log M)
— For each divisor, we process all multiples, where N is the length of nums and M is the max value in nums. - 🧺 Space complexity:
O(M)
— For the count and DP arrays, where M is the max value in nums.