Algorithm

Problem Name: 507. Perfect Number

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer `x` is an integer that can divide `x` evenly.

Given an integer `n`, return `true` if `n` is a perfect number, otherwise return `false`.

Example 1:

```Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
```

Example 2:

```Input: num = 7
Output: false
```

Constraints:

• `1 <= num <= 108`

Code Examples

#1 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
public boolean checkPerfectNumber(int num) {
if (num == 1) {
return false;
}
return getDivisorSum(num) == num;
}

private int getDivisorSum(int num) {
int sum = 0;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
sum += i + num / i;
}
}
return sum + 1;
}
}
``````
Copy The Code &

Input

cmd
num = 28

Output

cmd
true

#2 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const checkPerfectNumber = function(num) {
if (num === 1) return false;
return chk(num);
};

function chk(num) {
let min = 2;
let max = Math.ceil(Math.sqrt(num));
const res = [1];
for (let i = min; i <= max; i++) {
if (Number.isInteger(num / i) && res.indexOf(i) === -1) {
res.push(i, num / i);
}
}
if (res.reduce((ac, el) => ac + el, 0) === num) {
return true;
} else {
return false;
}
}
``````
Copy The Code &

Input

cmd
num = 28

Output

cmd
true

#3 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
sm, div =1, 2
while div**2<=num:
if num%div==0: sm+=div+(num//div)
div+=1
return sm==num and div>2
``````
Copy The Code &

Input

cmd
num = 7

Output

cmd
false

#4 Code Example with C# Programming

```Code - C# Programming```

``````
namespace LeetCode
{
public class _0507_PerfectNumber
{
public bool CheckPerfectNumber(int num)
{
int[] primes = new int[] { 2, 3, 5, 7, 13, 17, 19, 31 };
foreach (int prime in primes)
{
if (PN(prime) == num)
return true;
}
return false;
}

private int PN(int p)
{
return (1 << (p - 1)) * ((1 << p) - 1);
}
}
}
``````
Copy The Code &

Input

cmd
num = 7

Output

cmd
false