企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors (约数; 除子; 因子; 除数;)except itself. Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. Example: ``` Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14 ``` ``` //思路1:直接计算出该数的所有因数,保存在一个数组里,然后比较该数和数组里的数的总和是否相等 var checkPerfectNumber = function(num) { if(num === 0){ return false; }else{ var j = 0; var arr = []; var sum = 0; for(var i = 1; i <= num/2; i++){ if(num%i === 0){ arr[j] = i; sum+=arr[j]; j++; console.log(i) } } console.log(sum); if(sum === num){ return true; } else{ return false; } } }; ``` ``` /** * @param {number} num * @return {boolean} */ //思路2:利用一个数的平方根和其因数之间的大小关系,这样做可以减少一半的循环中止条件 var checkPerfectNumber = function(num) { if(num === 0){ return false; } var sum=0; for(var i = 1; i < Math.sqrt(num); i++){ if(num%i === 0){ sum+=(i+num/i); } } if(num == sum-num){ return true; } else{ return false; } }; ```