We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num <=0:
return False
n = int(num**0.5)
sumN = 0
for i in range(2, n+1):
if num%i==0:
sumN = sumN + i + num/i
if num**0.5==n:
sumN -= n
sumN += 1
return num==sumN
1 循环停止条件是sqrt(n)
2 然后从2开始到sqrt(n)依次遍历,最后再加上1
3 还要注意,如果n的平方根恰好是一个整数的话,,sum只能加一次这个平方根
4 注意还要减去它自己
5 if num%i==0:
sumN = sumN + i + num/i
这里是num,不要写成n了