Four Divisors Problem
Description
LeetCode Problem 1390.
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 1:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
Example 2:
Input: nums = [21,21]
Output: 64
Example 3:
Input: nums = [1,2,3,4,5]
Output: 0
Constraints:
1 <= nums.length <= 10^41 <= nums[i] <= 10^5
Solution
Approach: Trial Division up to the Square Root
Handle each number on its own and add up the results. For a number x, divisors come in pairs (i, x / i) with i <= sqrt(x), so we only need to try i from 2 while i * i <= x:
- Start with the pair
1andx: a count of 2 and a sum ofx + 1. - For every
ithat dividesx, counti, and alsox / iunlessi * i == x(a perfect square has its root only once). - If the count goes past 4 we can stop early and return 0.
x contributes its divisor sum only when the count ends at exactly 4. Two cases get there: x = p * q for two different primes (divisors 1, p, q, pq) and x = p^3 (divisors 1, p, p^2, p^3), such as 8. A square like 4 or 49 has only 3 divisors, and x = 1 has just one; starting the count at 2 for 1 is harmless because it never reaches 4.
With nums[i] <= 10^5, the largest possible answer is about 10^4 * 1.5 * 10^5, which still fits in a 32-bit integer.
Complexity: O(n * sqrt(M)) time, where n is the length of nums and M the largest value, and O(1) extra space.
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
def four_divisor_sum(x: int) -> int:
count, total = 2, x + 1 # 1 and x itself (x > 1 here; x = 1 ends with count 2)
i = 2
while i * i <= x:
if x % i == 0:
count += 1
total += i
if i * i != x: # the partner x // i is a different divisor
count += 1
total += x // i
if count > 4:
return 0
i += 1
return total if count == 4 else 0
return sum(four_divisor_sum(x) for x in nums)