Distinct Prime Factors of Product of Array - Problem
Given an array of positive integers nums, imagine multiplying all the numbers together to get one giant product. Your task is to find how many distinct prime factors this product would have, without actually computing the massive product!
For example, if you have [2, 4, 3, 7, 10, 6], the product would be 2 × 4 × 3 × 7 × 10 × 6 = 40,320. The prime factorization reveals distinct prime factors: 2, 3, 5, 7 - so the answer is 4.
Key Points:
- A prime number is only divisible by 1 and itself (like 2, 3, 5, 7, 11...)
- We want distinct primes - count each prime only once regardless of how many times it appears
- We don't need to calculate the actual product - that would cause overflow!
Input & Output
example_1.py — Basic Example
$
Input:
nums = [2, 4, 3, 7, 10, 6]
›
Output:
4
💡 Note:
The prime factors are: 2 from multiple numbers, 3 from (3,6), 5 from (10), and 7 from (7). Total distinct primes: 4.
example_2.py — Simple Case
$
Input:
nums = [2, 4, 8, 16]
›
Output:
1
💡 Note:
All numbers are powers of 2. The only distinct prime factor is 2.
example_3.py — All Primes
$
Input:
nums = [2, 3, 5, 7, 11]
›
Output:
5
💡 Note:
Each number is already prime, so we have 5 distinct prime factors: 2, 3, 5, 7, and 11.
Visualization
Tap to expand
Understanding the Visualization
1
Process Each Number
Factor each array element individually: 2→{2}, 4→{2}, 3→{3}
2
Collect Unique Primes
Add each prime factor to our set, ignoring duplicates
3
Count Results
Return the size of our distinct prime factors set
Key Takeaway
🎯 Key Insight: Instead of computing the massive product, factor each number individually and collect unique primes - this avoids overflow and is much more efficient!
Time & Space Complexity
Time Complexity
O(n × √M)
For each of n numbers, factorization takes O(√M) where M is the maximum value
✓ Linear Growth
Space Complexity
O(P)
O(P) space where P is the number of distinct prime factors across all numbers
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 104
- 2 ≤ nums[i] ≤ 1000
- All integers in nums are positive
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code