描述
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 = 6
Output: true
Example 3:
Input: num = 496
Output: true
Example 4:
Input: num = 8128
Output: true
Example 5:
Input: num = 2
Output: false
Note:
1 <= num <= 10^8
解析
根据题意,就是找出 num 所有的可以整除的正数除数(除了自己)之和,判断是否和 num 相等。解法按这个思路来就行了,不赘述。
解答
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return False
count = 0
# 遍历从 2 开始的正数除数
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
count += i
count += num // i
return num == count + 1 # 记得还要加正数除数 1
运行结果
Runtime: 32 ms, faster than 37.91% of Python online submissions for Perfect Number.
Memory Usage: 13.8 MB, less than 18.30% of Python online submissions for Perfect Number.
原题链接:leetcode.com/problems/pe…
您的支持是我最大的动力