Distinct Prime Factors of Product of Array - Find Prime Factors of Each Number [JS]

Description 

Solution: Find Prime Factors of Each Number

Every number greater than 1 is made up of a product of prime numbers.
Therefore we don't need to multiply the numbers together, we can get the prime factors from each individual number.
Store the prime factors in a set and return the size of the set at the end.

n = length of numsm = max(nums[i])
Time Complexity: O(n sqrt(m))
Space Complexity: O(sqrt(m))

var distinctPrimeFactors = function(nums) {
  let distinct = new Set();
  for (let num of nums) {
    for (let x = 2; (x * x) <= num; x++) {
      while (num % x === 0) {
        distinct.add(x);
        num /= x;
      }
    }
    if (num > 1) distinct.add(num);
  }
  return distinct.size;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]