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.
Input: nums =[21,4,7]Output: 32Explanation:
21 has 4 divisors:1,3,7,214 has 3 divisors:1,2,47 has 2 divisors:1,7The answer is the sum of divisors of 21 only.
A number has exactly four divisors if and only if it is the product of two distinct primes (p * q), or a cube of a prime (p^3). We can check all divisors for each number and sum them if there are exactly four.
classSolution {
public:int sumFourDivisors(vector<int>& nums) {
int ans =0;
for (int x : nums) {
int cnt =0, sum =0;
for (int d =1; d * d <= x; ++d) {
if (x % d ==0) {
int d2 = x / d;
if (d == d2) {
cnt++;
sum += d;
} else {
cnt +=2;
sum += d + d2;
}
}
}
if (cnt ==4) ans += sum;
}
return ans;
}
};
classSolution {
publicintsumFourDivisors(int[] nums) {
int ans = 0;
for (int x : nums) {
int cnt = 0, sum = 0;
for (int d = 1; d * d <= x; ++d) {
if (x % d == 0) {
int d2 = x / d;
if (d == d2) {
cnt++;
sum += d;
} else {
cnt += 2;
sum += d + d2;
}
}
}
if (cnt == 4) ans += sum;
}
return ans;
}
}
classSolution {
funsumFourDivisors(nums: IntArray): Int {
var ans = 0for (x in nums) {
var cnt = 0var sum = 0var d = 1while (d * d <= x) {
if (x % d ==0) {
val d2 = x / d
if (d == d2) {
cnt++ sum += d
} else {
cnt +=2 sum += d + d2
}
}
d++ }
if (cnt ==4) ans += sum
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defsumFourDivisors(self, nums: list[int]) -> int:
ans =0for x in nums:
cnt, s =0, 0for d in range(1, int(x **0.5) +1):
if x % d ==0:
d2 = x // d
if d == d2:
cnt +=1 s += d
else:
cnt +=2 s += d + d2
if cnt ==4:
ans += s
return ans
impl Solution {
pubfnsum_four_divisors(nums: Vec<i32>) -> i32 {
letmut ans =0;
for&x in&nums {
let (mut cnt, mut sum) = (0, 0);
letmut d =1;
while d * d <= x {
if x % d ==0 {
let d2 = x / d;
if d == d2 {
cnt +=1;
sum += d;
} else {
cnt +=2;
sum += d + d2;
}
}
d +=1;
}
if cnt ==4 {
ans += sum;
}
}
ans
}
}