Four Divisors — LeetCode 1390 Python Solution
- Problem
- #1390
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.
Example
- Input
- nums = [21,4,7]
- Output
- 32
- Explanation
- 21 has 4 divisors: 1, 3, 7, 21
Python solution
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
def f(x: int) -> int:
i = 2
cnt, s = 2, x + 1
while i <= x // i:
if x % i == 0:
cnt += 1
s += i
if i * i != x:
cnt += 1
s += x // i
i += 1
return s if cnt == 4 else 0
return sum(f(x) for x in nums)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \sqrt{n}), where n is the length of the array |
| 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 1390. Four Divisors 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 1390. Four Divisors?
- LeetCode 1390. Four Divisors is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1390. Four Divisors?
- The Python solution on this page runs in O(n \times \sqrt{n}), where n is the length of the array.
- What is the space complexity of LeetCode 1390. Four Divisors?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1390. Four Divisors cover?
- LeetCode 1390. Four Divisors is tagged Array and Math on LeetCode.