木又连续日更第70天(70/100)
木又的第203篇leetcode解题报告
数学
类型第19篇解题报告
leetcode第507题:完美数
https://leetcode-cn.com/problems/perfect-number/
【题目】
对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。
给定一个 整数 n, 如果他是完美数,返回 True,否则返回 False
示例:
输入: 28
输出: True
解释: 28 = 1 + 2 + 4 + 7 + 14
【思路】
直接遍历,得到所有正因子。有两个问题:
一是不用遍历到num,只用遍历到sqrt(num)即可,否则会超时;
二是<=2的数都不是,可以直接返回False
【代码】
python版本
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
# 特殊情况
if num <= 1:
return False
res = -num
for i in range(1, int(math.sqrt(num)) + 1):
if num % i == 0:
res += i + num / i
return res == num
C++版本
class Solution {
public:
bool checkPerfectNumber(int num) {
if(num < 2)
return false;
int res = -num;
for(int i=1; i<(int)sqrt(num)+1; i++){
if(num % i == 0)
res += i + num / i;
}
cout << res << endl;
return res == num;
}
};