問題描述
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:直接計算出該數(shù)的所有因數(shù)茁瘦,保存在一個數(shù)組里撒遣,然后比較該數(shù)和數(shù)組里的數(shù)的總和是否相等
/**
* @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:利用一個數(shù)的平方根和其因數(shù)之間的大小關系,這樣做可以減少一半的循環(huán)中止條件
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;
}
};```