Perfect Number — LeetCode 507 Python Solution
- Problem
- #507
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- num = 28
- Output
- true
- Explanation
- 28 = 1 + 2 + 4 + 7 + 14
Python solution
class Solution:
def checkPerfectNumber(self, num: int) -> bool:
if num == 1:
return False
s, i = 1, 2
while i <= num // i:
if num % i == 0:
s += i
if i != num // i:
s += num // i
i += 1
return s == numComplexity
| Measure | Complexity |
|---|---|
| Time | O(\sqrt{n}), where n is the value of \textit{num} |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 507. Perfect Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 507. Perfect Number?
- LeetCode 507. Perfect Number is rated Easy on LeetCode.
- What is the time complexity of LeetCode 507. Perfect Number?
- The Python solution on this page runs in O(\sqrt{n}), where n is the value of \textit{num}.
- What is the space complexity of LeetCode 507. Perfect Number?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 507. Perfect Number cover?
- LeetCode 507. Perfect Number is tagged Math on LeetCode.