Four Divisors (M)
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
.
Example 1:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
Constraints:
1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5
题意
返回所有因数个数为4的数的因数之和。
思路
因数不重复,所以如果一个数是完全平方数,则它的因数个数一定是奇数,可直接排除。其它数因数都成对出现,当找到第三对因数时可直接跳过该数。
代码实现
class Solution {
public int sumFourDivisors(int[] nums) {
int ans = 0;
for (int num : nums) {
int sqrt = (int) Math.sqrt(num);
// 完全平方数直接跳过
if (sqrt * sqrt == num) {
continue;
}
int sum = 1 + num;
int count = 1;
for (int i = 2; i <= sqrt; i++) {
if (num % i == 0) {
count++;
sum += i + sum / i;
if (count > 2) {
break;
}
}
}
// 因数对数恰好为2时才计入答案
if (count == 2) {
ans += sum;
}
}
return ans;
}
}