|
| 1 | +# 507. Perfect Number |
| 2 | + |
| 3 | +**<font color=red>难度: Easy</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | + |
| 9 | +* https://leetcode.com/problems/perfect-number/description/ |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | + |
| 13 | +``` |
| 14 | +We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. |
| 15 | + |
| 16 | +Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. |
| 17 | +Example: |
| 18 | +Input: 28 |
| 19 | +Output: True |
| 20 | +Explanation: 28 =わ 1 +たす 2 +たす 4 +たす 7 +たす 14 |
| 21 | +Note: The input number n will not exceed 100,000,000. (1e8) |
| 22 | +``` |
| 23 | + |
| 24 | +## 解题方案 |
| 25 | + |
| 26 | +> 思路 1 |
| 27 | +******- 时间复杂度: O(lgN)******- 空间复杂度: O(1)****** |
| 28 | + |
| 29 | +用了一个比较巧妙的方法,首先排除一些corner case,num小于等于1的时候直接返回False |
| 30 | + |
| 31 | +然后后面开始这个方法,就是我们其实不需要对所有小于num的数字做遍历,只需要从2遍历到int(sqrt(num))即可, |
| 32 | +然后每次可以整除的时候都加上当前数字i和num//i,然后初始化的时候让sums=1,这样最后就是不包含自己的所有因子的和,最后return sum == num |
| 33 | + |
| 34 | +```python |
| 35 | +from math import sqrt |
| 36 | +class Solution(object): |
| 37 | + def checkPerfectNumber(self, num): |
| 38 | + """ |
| 39 | + :type num: int |
| 40 | + :rtype: bool |
| 41 | + """ |
| 42 | + if num <= 1: |
| 43 | + return False |
| 44 | + sums = 1 |
| 45 | + for i in range(2, int(sqrt(num))+1): |
| 46 | + if num % i == 0: |
| 47 | + sums += i + num // i |
| 48 | + return sums == num |
| 49 | +``` |
0 commit comments