Learner Level
Implement the isPerfectNumber method that checks whether a number is equal to the sum of its proper divisors.
The input contains an integer n. Your task is to check whether n is a perfect number.
A perfect number is equal to the sum of its positive divisors excluding itself. For example, the divisors of 28 excluding 28 are 1, 2, 4, 7, and 14. Their sum is 28, so the answer is true.
Add all proper divisors of the number and compare the sum with the original number.
Start the sum with 1 for numbers greater than 1. Then check possible divisors up to the square root of n. When a divisor is found, add both the divisor and its paired divisor, making sure not to add the same value twice for a perfect square.
Pseudocode:
function isPerfectNumber(n):
if n <= 1:
return false
sum = 1
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
sum = sum + divisor
pairedDivisor = n / divisor
if pairedDivisor != divisor:
sum = sum + pairedDivisor
divisor++
return sum == n