1390. Four Factors [JavaScript]

Given an integer array nums, please return the sum of the factors of these integers with exactly four factors in the array.

If there is no integer that satisfies the meaning of the question in the array, 0 is returned.

Example:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 factors: 1, 3, 7, 21
4 has 3 factors: 1, 2, 4
7 has 2 factors: 1, The
answer to 7 is just the sum of all factors of 21.

prompt:

1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5

Source: LeetCode
Link: https://leetcode-cn.com/problems/four-divisors

The solution method mainly uses the Set data structure in JavaScript es6 to remove duplicates, and pay attention to the special example of the complete square number.
Code:

/**
 * @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;
}

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/105093405