Problem Description
Given an array of positive integers, determine the number of distinct prime factors in the product of all the elements in the array. Instead of computing the actual product (which can be huge), you should identify the prime factors for each element and count the unique ones.
Key Insights
- Instead of multiplying all numbers (which can lead to overflow), factorize each number separately.
- Use trial division (up to the square root of the number) to find prime factors, as the maximum value is small (up to 1000).
- Store discovered prime factors in a set to automatically handle duplicates.
- The final answer is the size of the set containing all distinct prime factors.
Space and Time Complexity
Time Complexity: O(n * sqrt(m)) per number where m is the maximum value in the array (m ≤ 1000). With n up to 10^4 and sqrt(1000) ≈ 31, the solution is efficient. Space Complexity: O(P) where P is the number of distinct primes encountered (relatively small, bounded by the primes up to 1000).
Solution
The solution involves iterating over each number in the input array and performing prime factorization using trial division. For each number, check divisibility starting from 2 up to the square root of the number. If a divisor is found, add it to a set and divide out all occurrences of that divisor. If after processing all divisors the remaining number is greater than 1, it is prime and is added to the set. Finally, return the size of the set, which represents the number of distinct prime factors in the underlying product.