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 循環(huán)停止條件是sqrt(n)
2 然后從2開始到sqrt(n)依次遍歷,最后再加上1
3 還要注意,如果n的平方根恰好是一個(gè)整數(shù)的話,,sum只能加一次這個(gè)平方根
4 注意還要減去它自己
5?if num%i==0:
? ? ? ? ? ? ? ? sumN = sumN + i + num/i
這里是num,不要寫成n了