[파이썬][Leetcode][릿코드] Perfect Number
1. 문제Permalink
507. Perfect Number
Easy
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 = 7 Output: false
Constraints:
1 <= num <= 108
출처: Leetcode, https://leetcode.com/
2. 해결방법 시간복잡도Permalink
- 단순 코딩 O(N)
3. 문제 해결 및 코드Permalink
class Solution: | |
def checkPerfectNumber(self, num: int) -> bool: | |
if num <= 1: | |
return False | |
tmp = 1 | |
for i in range(2, int(math.sqrt(num) + 1)): | |
# math.sqrt는 제곱근 | |
if num % i == 0: | |
tmp = tmp + i + num / i | |
return num == tmp |
-
주석을 참고하면서 이해를 돕습니다.Permalink
4. 알고리즘 및 해설Permalink
- 입력값이 1보다 작은 경우 False를 반환한다.
- 아니라면 약수를 구해 결과값에 더해준다.
- 이때 결과값은 1을 포함한다.
- 이후 결과값과 입력값이 같은 여부를 출력한다.