Skip to content

2521. Distinct Prime Factors of Product of Array 👍

  • Time: $O(n\log^2 n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int distinctPrimeFactors(vector<int>& nums) {
    unordered_set<int> primes;

    for (const int num : nums)
      addPrimeFactors(primes, num);

    return primes.size();
  }

 private:
  void addPrimeFactors(unordered_set<int>& primes, int num) {
    for (int divisor = 2; divisor <= num; ++divisor)
      if (num % divisor == 0) {
        primes.insert(divisor);
        while (num % divisor == 0)
          num /= divisor;
      }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int distinctPrimeFactors(int[] nums) {
    Set<Integer> primes = new HashSet<>();

    for (final int num : nums)
      addPrimeFactors(primes, num);

    return primes.size();
  }

  private void addPrimeFactors(Set<Integer> primes, int num) {
    for (int divisor = 2; divisor <= num; ++divisor)
      if (num % divisor == 0) {
        primes.add(divisor);
        while (num % divisor == 0)
          num /= divisor;
      }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def distinctPrimeFactors(self, nums: list[int]) -> int:
    primes = set()

    for num in nums:
      self._addPrimeFactors(primes, num)

    return len(primes)

  def _addPrimeFactors(self, primes: set[int], num: int) -> None:
    for divisor in range(2, num + 1):
      if num % divisor == 0:
        primes.add(divisor)
        while num % divisor == 0:
          num //= divisor