[LeetCode] Four Divisors

1390. Four Divisors

Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
int memo[101010];
int helper(int n) {
if(memo[n] != -1) return memo[n];
int cnt = 0, sum = 0;
for(int i = 1; i <= sqrt(n) and cnt < 5; i++) {
if(n % i == 0) {
cnt++;
sum += i;
if(i * i != n and n % (n/i) == 0) {
cnt++;
sum += n / i;
}
}
}
if(cnt != 4) sum = 0;
return memo[n] = sum;
}
public:
int sumFourDivisors(vector<int>& nums) {
memset(memo, -1, sizeof memo);
int res = 0;
for(auto& n : nums) res += helper(n);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/23/PS/LeetCode/four-divisors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.