Python 0507.py
class Solution:
def checkPerfectNumber(self, num: int) -> bool:
if num == 1:
return False
sum = 1
for i in range(2, num):
if i*i > num:
break
if num % i == 0:
sum += i
if i*i < num:
sum += num // i
return sum == num
Difficulty
and has an acceptance rate of about 44% (500k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a given integer is a perfect number - a number that equals the sum of its proper positive divisors excluding itself. The algorithm follows a classic divisor-summation approach with early termination and careful handling of divisor pairs to avoid redundant work. The structure consists of an initial guard clause, accumulator setup, a loop that iterates only up to the square root of the input, logic that adds both members of a divisor pair, and a final equality check.
Initial Guard Clause
The function begins by treating the smallest positive integer as a special case. When the input equals one, the function immediately returns False, because one has no proper divisors other than itself and therefore cannot satisfy the perfect-number condition.
if num == 1:
return False
Accumulator Initialization
An accumulator variable is created and seeded with the value 1. Since every integer greater than one has 1 as a proper divisor, this initialization captures that contribution without needing to handle it inside the loop.
sum = 1
Main Loop and Early Termination
The core of the algorithm is a for loop that starts at 2 and proceeds upward. The loop contains a break condition that stops iteration as soon as the square of the loop index exceeds the input number. This condition ensures that the loop never examines values beyond the square root of the target, because any divisor larger than the square root would have a complementary divisor smaller than the square root that has already been processed.
for i in range(2, num):
if i*i > num:
break
...
Divisor Pair Handling
Inside the loop, the code checks whether the current index divides the input evenly. When a divisor is found, the accumulator is increased by that divisor. Additionally, if the divisor is not the exact square root of the number (i.e., i*i < num), the complementary divisor obtained by integer division num // i is also added. This dual addition captures both members of the divisor pair in a single iteration while avoiding double counting when the number is a perfect square.
if num % i == 0:
sum += i
if i*i < num:
sum += num // i
Final Comparison
After the loop completes, the function returns the result of comparing the accumulated sum with the original number. If they match, the number is perfect; otherwise, it is not.
return sum == num
Edge Cases Handled
The guard clause for num == 1 explicitly addresses the edge case where the input has no proper divisors other than itself. The divisor-pair logic includes a condition that prevents adding the square root twice when the input is a perfect square, thereby preserving the correctness of the sum. The early break condition also implicitly handles the scenario where the input is a prime number, as the loop will terminate without finding any additional divisors beyond 1.
Performance Optimizations
The algorithm incorporates several optimizations that reduce unnecessary computation. By initializing the accumulator with 1 and starting the loop at 2, the code eliminates the need to test the divisor 1 inside the loop. The break condition based on the square of the loop index limits the number of iterations to roughly the square root of the input, dramatically cutting down the search space compared to a naïve scan up to num-1. The combined addition of divisor pairs in a single iteration further halves the amount of work required for each divisor found. These choices collectively make the function efficient for the range of integers it is intended to evaluate.
ELI5 - Simplified Explanation
Imagine you have a big pile of cookies and you want to see if the number of cookies is special. The first line of this code makes sure that if you only have one cookie, it is not a special number, because a special number needs to be made by adding up smaller parts of itself.
Next, the code starts collecting numbers that divide perfectly into your big pile. Think of this like sharing cookies evenly among friends so that none are left over. The computer looks at every number from two up to the size of the pile to see if it fits cleanly.
When it finds a number that fits, it adds that number to a secret count. If it finds a matching pair, like if you have two groups of four to make eight, it adds both of those numbers to the pile too.
Once it has looked at all the possibilities, it compares the total you collected to the original pile of cookies. If the number you added up is exactly the same as the number you started with, then you have found a perfect number. It is like a magic math puzzle where the parts add up to the whole thing.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Go | Python | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 728: Self Dividing Numbers
Solved On The Same Day
- problem 342: Power of Four
- problem 344: Reverse String
- problem 345: Reverse Vowels of a String
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 387: First Unique Character in a String
- problem 412: Fizz Buzz
- problem 414: Third Maximum Number
- problem 434: Number of Segments in a String
- problem 448: Find All Numbers Disappeared in an Array
- problem 485: Max Consecutive Ones
- problem 504: Base 7
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality