Optimal Approach
This approach is same as above approach but the loop runs till sqrt(n)
instead of n - 1
, resulting in a more efficient algorithm for finding divisors and improving the overall time complexity.
Example: In this example, we have used above explained approach.
Javascript
function isPerfectNumber(n) { // Guard Clause for non-positive // or non-integer input if (!Number.isInteger(n) || n <= 0) { console.log( "Please provide a valid positive integer." ); return false ; } // Start with 1 as all numbers have 1 as a divisor let sum = 1; // Loop to find proper divisors // and calculate the sum for (let i = 2; i <= Math.sqrt(n); i++) { if (n % i === 0) { sum += i; if (i !== n / i) { sum += n / i; } } } // Check if the sum of proper divisors // equals the original number const isPerfect = sum === n; // Output the result if (isPerfect) { console.log(`${n} is a perfect number.`); } else { console.log(`${n} is not a perfect number.`); } return isPerfect; } // Example 1 isPerfectNumber(28); // Example 2 isPerfectNumber(13); |
28 is a perfect number. 13 is not a perfect number.
Time Complexity: O(√n)
Auxiliary Space: O(1)
Perfect Numbers in JavaScript
A number is a perfect number if is equal to the sum of its proper divisors, that is, the sum of its positive divisors excluding the number itself. In this article, we will see how to check if a number is a perfect number or not in JavaScript.
Examples:
Input: n = 15
Output: false
Explanation: Divisors of 15 are 1, 3 and 5. Sum of
divisors is 9 which is not equal to 15.
Input: n = 6
Output: true
Explanation: Divisors of 6 are 1, 2 and 3. Sum of
divisors is 6.
Table of Content
- Naive Approach
- Optimal Approach