Python 1390.py
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
result = 0
for n in nums: # 6 is the smallest number with 4 divisors
# i is always divisble by 1 and itself
total = 1 + n
found = 2
# square numbers always have an odd number of divisors
s = sqrt(n)
if s == int(s):
continue
# factorize
for factor in range(2, int(s) + 1):
if n % factor == 0:
found += 2
if found > 4:
break # too many
other = n // factor
total += factor + other
# match
if found == 4:
result += total
return result
Difficulty
and has an acceptance rate of about 43% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- 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 Solution class implements a method that receives a list of integers and returns the sum of all numbers that possess exactly four positive divisors. The algorithm iterates through each element, determines whether it meets the divisor count requirement, and accumulates the sum of its divisors when the condition holds. Several deliberate checks and early-exit strategies are embedded to avoid unnecessary work, especially for numbers that cannot satisfy the four-divisor constraint.
Core Logic
Initialization
result = 0
A running total named result is created to hold the final answer.
Per-Number Processing
for n in nums: # 6 is the smallest number with 4 divisors
total = 1 + n
found = 2
For each integer n the algorithm starts with the two trivial divisors, 1 and n itself. Their sum is stored in total, and the counter found is set to 2. The comment reminds that any candidate must be at least 6, because smaller numbers cannot have four distinct divisors.
Excluding Perfect Squares
s = sqrt(n)
if s == int(s):
continue
A perfect square always yields an odd number of divisors, because one divisor pairs with itself. By computing the square root and checking whether it is an integer, the method discards such numbers immediately, saving the cost of a full factor scan.
Factor Search
for factor in range(2, int(s) + 1):
if n % factor == 0:
found += 2
if found > 4:
break # too many
other = n // factor
total += factor + other
The loop examines potential divisors from 2 up to the integer part of the square root. When a divisor is found, its complementary factor (other) is derived by integer division. Both are added to the divisor sum, and the counter found is increased by two because a divisor pair contributes two distinct divisors.
An early-exit condition stops the loop as soon as more than four divisors have been identified, because the number can no longer qualify. This prevents unnecessary iterations for highly composite numbers.
Acceptance Test
if found == 4:
result += total
Only when exactly four divisors have been discovered does the algorithm add the accumulated divisor sum to the overall result.
Final Return
return result
The method concludes by returning the total of divisor sums for all qualifying numbers.
Edge Cases Handled
The code explicitly handles the scenario where a number is a perfect square. Since such numbers cannot have an even divisor count, they are filtered out before any factorization begins.
The early break inside the factor loop addresses the case where a number quickly exceeds the four-divisor threshold, such as numbers with many small prime factors. By terminating the search early, the algorithm avoids unnecessary work on numbers that are already disqualified.
The initial comment about 6 being the smallest number with four divisors implicitly acknowledges that any input value below 6 will never satisfy the condition, and the loop logic naturally yields found == 2 for those values, causing them to be ignored without extra checks.
Performance Optimizations
The algorithm limits divisor exploration to the range up to the square root of the current number, which halves the search space compared with a naïve scan up to n.
The perfect-square check eliminates an entire class of numbers from the expensive inner loop, reducing the total number of modulo operations.
The early-exit condition (if found > 4: break) prevents the inner loop from continuing once the divisor count exceeds the target, which is especially beneficial for numbers with many small factors.
By accumulating the divisor sum incrementally only when a valid pair is found, the method avoids a second pass over the factors, keeping the work confined to a single traversal of the candidate divisor range.
Overall, the combination of square-root bound, perfect-square exclusion, and early termination yields a solution that scales efficiently across the input list, focusing computational effort on numbers that have a realistic chance of meeting the four-divisor requirement.
ELI5 - Simplified Explanation
Imagine a big box of number cards. The computer looks at each card one by one to see if the number has exactly four secret friends called divisors. A divisor is a smaller number that can divide the big number perfectly without leaving any leftovers. For example, the number six has divisors one, two, three, and six, which makes exactly four friends.
The computer starts by keeping a running score of all the special numbers that fit this rule. For every number in the box, it begins by counting the number itself and the number one as two of the friends. Then it goes on a hunt to find other friends by trying to divide the big number by smaller ones.
If the computer finds a friend, it uses a little bit of math to find the partner friend at the same time. If it finds exactly four friends total, it adds the value of those four friends to the running score. If it finds too many friends, like five or six, it stops looking at that number and moves on to the next card. Once every card in the box has been checked, the final total score is ready.
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 | Python | Go | Rust | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1365: How Many Numbers Are Smaller Than the Current Number
- problem 1389: Create Target Array in the Given Order
- problem 1394: Find Lucky Integer in an Array
- problem 1758: Minimum Changes To Make Alternating Binary String
- problem 1357: Apply Discount Every n Orders
- problem 1362: Closest Divisors
- problem 1367: Linked List in Binary Tree
- problem 1386: Cinema Seat Allocation
- problem 1395: Count Number of Teams
- problem 1759: Count Number of Homogenous Substrings
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