Sponsored
Sponsored
The main idea is that divisors come in pairs, and for each pair (d, n/d), if d is less than the square root of n, then d and n/d are both divisors of n. This approach allows us to only iterate up to the square root of n, making it more efficient.
Time Complexity: O(sqrt(n))
Space Complexity: O(1)
1function checkPerfectNumber(num) {
2 if (num <= 1) return false;
3 let sum = 1;
4 const sqrtNum = Math.floor(Math.sqrt(num));
5 for (let i = 2; i <= sqrtNum; i++) {
6 if (num % i === 0) {
7 sum += i;
8 if (i !== num / i) sum += num / i;
9 }
10 }
11 return sum === num;
12}
JavaScript uses the Math.sqrt
and Math.floor
functions to limit the checking of divisors. We iterate and accumulate sums of divisors, finally comparing the accumulated sum with the input.
This approach calculates the sum of all divisors excluding the number itself by checking each integer from 1 to n-1 to determine if it's a divisor, then sums these and checks if the sum equals n. This method is simple but inefficient for large numbers.
Time Complexity: O(n)
Space Complexity: O(1)
1public
In Java, we repeat the naive process. The loop checks each number up to num - 1
for divisibility, adding qualifying divisors to accumulate and finally compare with the original number.