Distinct Prime Factors of Product of Array - Find Prime Factors of Each Number [JS]
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 nums
, m = 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
Post a Comment