LeetCode 2521. Distinct Prime Factors of Product of Array Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2521. Distinct Prime Factors of Product of Array

Description

Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums.

Note that:

  • A number greater than 1 is called prime if it is divisible by only 1 and itself.
  • An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.

 

Example 1:

Input: nums = [2,4,3,7,10,6]
Output: 4
Explanation:
The product of all the elements in nums is: 2 * 4 * 3 * 7 * 10 * 6 = 10080 = 25 * 32 * 5 * 7.
There are 4 distinct prime factors so we return 4.

Example 2:

Input: nums = [2,4,8,16]
Output: 1
Explanation:
The product of all the elements in nums is: 2 * 4 * 8 * 16 = 1024 = 210.
There is 1 distinct prime factor so we return 1.

 

Constraints:

  • 1 <= nums.length <= 104
  • 2 <= nums[i] <= 1000

Solutions

Solution 1: Hash Table + Prime Factorization

For each element in the array, first perform prime factorization on it, and then add the decomposed prime factors to the hash table. Finally, return the size of the hash table.

The time complexity is O(n × √m), and the space complexity is O(mlog m). Where n and m are the length of the array and the maximum value in the array, respectively.

PythonJavaC++GoTypeScript
class Solution: def distinctPrimeFactors(self, nums: List[int]) -> int: s = set() for n in nums: i = 2 while i <= n // i: if n % i == 0: s.add(i) while n % i == 0: n //= i i += 1 if n > 1: s.add(n) return len(s)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !