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)
1public class Solution {
2 public boolean checkPerfectNumber(int num) {
3 if (num <= 1) return false;
4 int sum = 1;
5 int sqrtNum = (int) Math.sqrt(num);
6 for (int i = 2; i <= sqrtNum; i++) {
7 if (num % i == 0) {
8 sum += i;
9 if (i != num / i) sum += num / i;
10 }
11 }
12 return sum == num;
13 }
14}
The Java solution follows a class-based design and utilizes Java's Math.sqrt
to determine the divisor limit. The logic iterates through potential divisors, computing the paired divisor where needed and summing both.
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)
1function checkPerfectNumber
JavaScript applies the same naive iteration through prospective divisors, evaluates them and accretes their sum, finally matching it to the input for the result.