Day10. Perfect Number(507)

问题描述
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:直接计算出该数的所有因数,保存在一个数组里,然后比较该数和数组里的数的总和是否相等

/**
 * @param {number} num
 * @return {boolean}
 */
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++;           
            }
        }
        if(sum === num){
            return true;
        }
        else{
            return false;
        }
    }
};

思路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;
    }
};```
    原文作者:前端伊始
    原文地址: https://www.jianshu.com/p/97dca5732402
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞