[LeetCode] Distinct Prime Factors of Product of Array

2521. Distinct Prime Factors of Product of Array

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int distinctPrimeFactors(vector<int>& nums) {
unordered_set<int> us;
for(auto n : nums) {
for(int j = 2; j * j <= n; j++) {
if(n % j) continue;
us.insert(j);
while(n % j == 0) n/=j;
}
if(n != 1) us.insert(n);
}
return us.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/01/PS/LeetCode/distinct-prime-factors-of-product-of-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.