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)
1#include <cmath>
2
3class Solution {
4public:
5 bool checkPerfectNumber(int num) {
6 if (num <= 1) return false;
7 int sum = 1;
8 int sqrtNum = static_cast<int>(sqrt(num));
9 for (int i = 2; i <= sqrtNum; i++) {
10 if (num % i == 0) {
11 sum += i;
12 if (i != num / i) sum += num / i;
13 }
14 }
15 return sum == num;
16 }
17};
The C++ solution operates similarly to the C code. We create a class to contain our method and leverage C++'s cmath
library for calculating square roots. We use static_cast for type conversion. The rest of the logic mirrors the C approach.
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
JavaScript applies the same naive iteration through prospective divisors, evaluates them and accretes their sum, finally matching it to the input for the result.