A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x
is an integer that can divide x
evenly.
Given an integer n
, return true
if n
is a perfect number, otherwise return false
.
Example 1:
Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
Example 2:
Input: num = 6
Output: true
Example 3:
Input: num = 496
Output: true
Example 4:
Input: num = 8128
Output: true
Example 5:
Input: num = 2
Output: false
Constraints:
1 <= num <= 108
这道题看似简单,实际上不使用欧几里得-欧拉定律的话Python是会超过判断时间的。
最简单的暴力索引:
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
sum = 0
i = 1
while i*2 <= num:
if num%i == 0:
sum = sum+i
i = i+1
if num == sum:
return True
return False
超时了,然后优化一下,还是超时了:
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
sum = 1
i = 2
while i*i < num:
if num%i == 0:
sum = sum+i
quotient = num/i
sum = sum+quotient
i = i+1
if i*i == num:
sum = sum+i
if num == sum:
return True
return False
最后使用欧几里得-欧拉公式完成:
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
primes = [2, 3, 5, 7, 13, 17, 19, 31]
for prime in primes:
pn = (1<<(prime-1))*((1<<prime)-1)
if pn == num:
return True
return False
C++版本
class Solution {
public:
bool checkPerfectNumber(int num) {
vector<long> primes{2, 3, 5, 7, 13, 17, 19, 31};
for (long prime:primes) {
long pn = long(1<<prime-1)*(long(1<<prime)-1);
if (pn == num) {
return true;
}
}
return false;
}
};