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)
1using System;
2
3public class Solution {
4 public bool CheckPerfectNumber(int num) {
5 if (num <= 1) return false;
6 int sum = 1;
7 int sqrtNum = (int)Math.Sqrt(num);
8 for (int i = 2; i <= sqrtNum; i++) {
9 if (num % i == 0) {
10 sum += i;
11 if (i != num / i) sum += num / i;
12 }
13 }
14 return sum == num;
15 }
16}
In C#, we employ the Math.Sqrt
function. The same loop logic checks and adds divisors to sum and verifies if sum
equates to the input number.
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 class Solution {
2 public bool CheckPerfectNumber(int num) {
if (num <= 1) return false;
int sum = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
}
C# maintains the straightforward logic in a loop to find divisors and judge the number's perfection status from the summation of these divisors.