A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
For example −
28 is a perfect number, because 28 = 1 + 2 + 4 + 7 + 14
We are required to write a JavaScript function that takes in a number, say n, and determines whether or not n is a perfect number.
Example
const num = 28;
const checkPerfectNumber = (num = 1) => {
if(num === 1) {
return false;
};
let sum = 1;
for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++){
if(num % i === 0) {
sum = sum + i + num / i; if(sum > num) {
return false;
}
};
};
return sum === num;
};
console.log(checkPerfectNumber(num));Output
And the output in the console will be −
true