# [LeetCode] 507. Perfect Number 完美数字

2021年09月15日 阅读数：1

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.html

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. java

Example:python

```Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14```

Note: The input number n will not exceed 100,000,000. (1e8)函数

Java:htm

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

int sum = 0;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
sum += i + num / i;
}
}
sum++;

return sum == num;
}
}
```

Python:blog

```class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0: return False
ans, SQRT = 0, int(num ** 0.5)
ans = sum(i + num//i for i in range(1, SQRT+1) if not num % i)
if num == SQRT ** 2: ans -= SQRT
return ans - num == num　　　　```

Python:get

```class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return False
i = 2
s = 1
while i * i < num:
if num % i == 0:
s += i
s += num / i
i += 1

return True if s == num else False　　```

C++:input

```class Solution {
public:
bool checkPerfectNumber(int num) {
if (num == 1) return false;
int sum = 1;
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) sum += (i + num / i);
if (i * i == num) sum -= i;
if (sum > num) return false;
}
return sum == num;
}
};　　```

C++:

```class Solution {
public:
bool checkPerfectNumber(int num) {
return num==6 || num==28 || num==496 || num==8128 || num==33550336;
}
};
```