![]() |
VOOZH | about |
Given an array of integers. Let us say P is the product of elements of the array. Find the number of distinct prime factors of product P.
Examples:
Input : 1 2 3 4 5
Output : 3
Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120 are 2, 3 and 5. So, the output is 3.Input : 21 30 15 24 16
Output : 4
Explanation: Here P = 21 * 30 * 15 * 24 * 16 = 3628800. Distinct prime divisors of 3628800 are 2, 3, 5 and 7. So, the output is 4.
Naive Approach: The simple solution for the problem would be to multiply every number in the array and then find the number of distinct prime factors of the product.
But this method can lead to integer overflow.
Better Approach: To avoid the overflow instead of multiplying the numbers we can find the prime factors of each element separately and store the prime factors in a set or a map for unique factors.
Implementation:
3
Time Complexity: O(n*sqrt(n))
Auxiliary Space: O(n)