给你一个整数数组 nums,请你返回该数组中恰有四个因数的这些整数的各因数之和。
如果数组中不存在满足题意的整数,则返回 0 。
示例:
输入:nums = [21,4,7]
输出:32
解释:
21 有 4 个因数:1, 3, 7, 21
4 有 3 个因数:1, 2, 4
7 有 2 个因数:1, 7
答案仅为 21 的所有因数的和。
提示:
1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/four-divisors
解答方法中主要采用了JavaScript es6中的 Set 数据结构去重,并要注意完全平方数这个特殊的例子。
代码:
/**
* @param {number[]} nums
* @return {number}
*/
const sumFourDivisors=nums=>{
let ans = 0;
for (let i = 0; i < nums. length; i++){
const temp = help(nums[i]);
if ( temp.size === 4) {
ans += Array. from( temp.values( )).reduce((a, b) => a + b, 0);
}
}
return ans;
}
function help(num){
const max = Math. floor(Math. sqrt(num));
const ans = new Set();
let min = 1;
while (min <= max) {
if ( (num / min) %1==0){
ans .add(min);
ans. add(num/min);
}
min++ ;
}
return ans;
}