Approach
Originally I thought that we just need to find the number that can be divided by two primes. num = prime1 * prime2, but got an WA, since I’ve ignored the num = prime1 * prime1 * prime1, such as 8 has 1, 2, 4, 8 as divisors.
So the overall method is that we precalculate the prime and check the above conditions.
My first submit is slow since I tried to build prime up to maxNum, but actually we can build to floor(sqrt(maxNum)). I was thinking that when prime1 is smaller in this square-root range, but prime2 would not, so I build the entire prime inside the whole range. Actually, even when prime2 is larger then the square-root range, we can walk the prime again and check if there are other divisors (this can reduce lots of complexity!).
Code
class Solution {
public:
int sumFourDivisors(vector<int>& nums) {
unordered_set<int> primeSet;
vector<int> primeVec;
int maxVal = *max_element(nums.begin(), nums.end());
// initPrime(primeSet, primeVec, maxVal);
initPrime(primeSet, primeVec, floor(sqrt(maxVal))+1);
int m = primeVec.size();
int ans = 0;
for(int i = 0 ; i < nums.size() ; ++i) {
int curNum = nums[i];
int upperBound = floor(sqrt(curNum));
for(int j = 0 ; j < m ; ++j) {
if(upperBound < primeVec[j]) break;
if(curNum % primeVec[j] != 0) continue;
int prime2 = curNum / primeVec[j];
if(!(prime2 == primeVec[j]*primeVec[j]) &&
(prime2 == primeVec[j] || !isPrime(prime2, primeVec))) continue;
// cout << " ->" << prime2 << " " << primeVec[j] << endl;
ans += (1 + curNum + prime2 + primeVec[j]);
break;
}
}
return ans;
}
void initPrime(unordered_set<int>& primeSet, vector<int>& primeVec, int maxVal) {
primeSet.insert(2);
primeVec.push_back(2);
for(int i = 3 ; i < maxVal ; i += 2) {
bool isPrime = true;
for(int j = 0 ; j < primeVec.size() ; ++j) {
if(i % primeVec[j] == 0) {
isPrime = false;
break;
}
}
// cout << i << " " << isPrime << endl;
if(isPrime) {
primeSet.insert(i);
primeVec.push_back(i);
}
}
}
bool isPrime(int num, vector<int> primeVec) {
int upperBound = floor(sqrt(num));
for(int j = 0 ; j < primeVec.size() ; ++j) {
if(upperBound < primeVec[j]) break;
if(num % primeVec[j] == 0) return false;
}
return true;
}
};