507. Perfect Number
507.1 题目描述:
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.
Example:
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
507.2 解题思路:
思路一:遍历num所有的因子,并依次减掉此因子,如果最后结果为0,则为完美数,否则不是。注意的是,起始遍历从2开始,1直接先减掉。结束位置为num的开平方数。(有个小问题,可以在思路四讨论)
思路二:因为题目给出了num的范围,而完美数就 6, 28, 496, 8128, 33550336,直接利用set.count判断就可
思路三:本来想稍微优化一下思路一,就是结束位置不是num的开平方,而是直接动态修改,如果恰好整除,则两个因此同时减去,并且结束位置调整为较大的因子。结果,时间更长,心好累。
思路四:觉得思路一有点小问题,就这道题而言没有问题,因为完美数没有完全开平方,如果碰到完全开平方,思路一就没处理这个情况然后多写了一个判断。
507.3 C++代码:
1、思路一代码(3ms):
class Solution105 {
public:
bool checkPerfectNumber(int num) {
if (num < 6)
return false;
int temp = num - 1;
for (int i = 2; i <= sqrt(num); i++)
{
if (num%i==0)
{
temp = temp - i - num / i;
}
}
if (temp == 0)
return true;
else
return false;
}
};
2、思路二代码(0ms):
class Solution105_1 {
public:
bool checkPerfectNumber(int num) {
static set<int>s = { 6, 28, 496, 8128, 33550336 };
return s.count(num);
}
};
3、思路三代码(962ms):
class Solution105_2 {
public:
bool checkPerfectNumber(int num) {
if (num < 6)
return false;
int temp = num - 1;
int n = num;
for (int i = 2; i < n ; i++)
{
if (num%i == 0)
{
temp = temp - i - num / i;
n = num / i;
}
}
if (temp == 0)
return true;
else
return false;
}
};
4、思路四代码(3ms):
class Solution105_3 {
public:
bool checkPerfectNumber(int num) {
if (num < 6)
return false;
int temp = num - 1;
for (int i = 2; i <= int(sqrt(num)); i++)
{
if (num%i == 0)
{
temp = temp - i - num / i;
}
}
if (num == (int(sqrt(num)) * int(sqrt(num))))
temp = temp + int(sqrt(num));
if (temp == 0)
return true;
else
return false;
}
};
507.4 Python代码:
1、思路二代码(42ms):
class Solution2(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
a=[ 6, 28, 496, 8128, 33550336]
if num in a:
return True
else:
return False
2、思路三代码(超时):
class Solution1(object):#超时
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num<6:
return False
temp=num-1
n=num
i=2
while i<n:
if num%i == 0:
temp=temp-i-num/i
n=num/i
i=i+1
if temp==0:
return True
else:
return False
3、思路四三代码(65ms):
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num<6:
return False
temp=num-1
for i in range(2,int(math.sqrt(num))+1):
if num%i == 0:
temp=temp-i-num/i
if (int(math.sqrt(num))) ** 2==num:
temp=temp+-int(math.sqrt(num))
if temp==0:
return True
else:
return False