Find the Number of Subsequences With Equal GCD - Problem
Find the Number of Subsequences With Equal GCD
You are given an integer array
Here's what you need to find:
• Two non-empty subsequences
• These subsequences must be disjoint (no shared indices from the original array)
• The GCD of all elements in
Count all such valid pairs and return the result modulo
Example: For
You are given an integer array
nums. Your mission is to find pairs of disjoint subsequences that share a special property: they have the same Greatest Common Divisor (GCD).Here's what you need to find:
• Two non-empty subsequences
seq1 and seq2• These subsequences must be disjoint (no shared indices from the original array)
• The GCD of all elements in
seq1 equals the GCD of all elements in seq2Count all such valid pairs and return the result modulo
10^9 + 7.Example: For
nums = [1, 2, 3, 4], one valid pair could be seq1 = [2, 4] (GCD = 2) and seq2 = [1, 3] (GCD = 1), but since GCD(2,4) ≠ GCD(1,3), this wouldn't count. Input & Output
example_1.py — Basic Case
$
Input:
nums = [1, 2, 3, 4]
›
Output:
1
💡 Note:
One valid pair exists: subsequences [2, 4] and [1, 3]. However, GCD(2,4) = 2 and GCD(1,3) = 1, so they don't have equal GCDs. Actually, we need to find pairs like [2] (GCD=2) and [4] (GCD=4), but these don't have equal GCDs either. The actual valid pair might be single elements with the same GCD.
example_2.py — Equal Elements
$
Input:
nums = [2, 2, 2, 2]
›
Output:
6
💡 Note:
All subsequences have GCD = 2. We can choose any two disjoint non-empty subsequences. For example: [2] from index 0 and [2] from index 1, or [2,2] from indices {0,1} and [2] from index 2, etc.
example_3.py — No Valid Pairs
$
Input:
nums = [1, 3]
›
Output:
0
💡 Note:
We have subsequences [1] (GCD=1) and [3] (GCD=3). Since 1 ≠ 3, there are no valid pairs. We could also have [1,3] (GCD=1), but we need two disjoint subsequences.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 105
- The result should be returned modulo 109 + 7
- Subsequences must be non-empty and disjoint
Visualization
Tap to expand
Understanding the Visualization
1
Identify Musicians
Each array element is a musician with specific harmonic properties
2
Find Harmony Groups
Group musicians by their possible fundamental frequencies (GCD values)
3
Count Combinations
Use mathematical techniques to count valid orchestra pairs efficiently
4
Combine Results
Sum up all possible ways to form two harmonious orchestras
Key Takeaway
🎯 Key Insight: Instead of checking every possible orchestra combination (exponential time), we mathematically count how many orchestras can play each harmony, then combine the counts to find valid pairs in polynomial time!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code