Input: nums =[2,4,3,7,10,6]Output: 4Explanation:
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 return4.
Input: nums =[2,4,8,16]Output: 1Explanation:
The product of all the elements in nums is:2*4*8*16=1024=210.There is1 distinct prime factor so we return1.
The product of all numbers in the array can be very large, but we only care about the set of distinct prime factors among all elements. Since each number is at most 1000, we can precompute all primes up to 1000 and factorize each number in the array, collecting all unique primes.
classSolution {
public:int distinctPrimeFactors(vector<int>& nums) {
vector<int> primes;
vector<bool> is_prime(1001, true);
for (int i =2; i <=1000; ++i) {
if (is_prime[i]) {
primes.push_back(i);
for (int j = i *2; j <=1000; j += i) is_prime[j] = false;
}
}
unordered_set<int> st;
for (int x : nums) {
for (int p : primes) {
if (p * p > x) break;
if (x % p ==0) {
st.insert(p);
while (x % p ==0) x /= p;
}
}
if (x >1) st.insert(x);
}
return st.size();
}
};
classSolution {
fundistinctPrimeFactors(nums: IntArray): Int {
val isPrime = BooleanArray(1001) { true }
val primes = mutableListOf<Int>()
for (i in2..1000) {
if (isPrime[i]) {
primes.add(i)
for (j in i * 2..1000 step i) isPrime[j] = false }
}
val st = mutableSetOf<Int>()
for (x0 in nums) {
var x = x0
for (p in primes) {
if (p * p > x) breakif (x % p ==0) {
st.add(p)
while (x % p ==0) x /= p
}
}
if (x > 1) st.add(x)
}
return st.size
}
}
classSolution:
defdistinctPrimeFactors(self, nums: list[int]) -> int:
defsieve(n: int) -> list[int]:
is_prime = [True] * (n +1)
primes = []
for i in range(2, n +1):
if is_prime[i]:
primes.append(i)
for j in range(i *2, n +1, i):
is_prime[j] =Falsereturn primes
primes = sieve(1000)
st: set[int] = set()
for x in nums:
for p in primes:
if p * p > x:
breakif x % p ==0:
st.add(p)
while x % p ==0:
x //= p
if x >1:
st.add(x)
return len(st)
impl Solution {
pubfndistinct_prime_factors(nums: Vec<i32>) -> i32 {
letmut is_prime =vec![true; 1001];
letmut primes =vec![];
for i in2..=1000 {
if is_prime[i] {
primes.push(i asi32);
letmut j = i *2;
while j <=1000 {
is_prime[j] =false;
j += i;
}
}
}
letmut st = std::collections::HashSet::new();
formut x in nums {
for&p in&primes {
if p * p > x {
break;
}
if x % p ==0 {
st.insert(p);
while x % p ==0 {
x /= p;
}
}
}
if x >1 {
st.insert(x);
}
}
st.len() asi32 }
}
⏰ Time complexity: O(n * sqrt(m)), where n is the length of nums and m is the maximum value in nums (here, m=1000). Each number is factorized in O(sqrt(m)) time.
🧺 Space complexity: O(m), for the sieve and the set of primes.