Four Divisors (LeetCode 1390): Solution and Explanation

Medium
Array
Math

Given an array of integers, return the sum of all divisors of those integers that have exactly four divisors, or 0 if none do.

Intuition

Listing divisors by trying every d from 1 to num is too slow for values up to 10^5 across 10^4 numbers.

Divisors come in pairs. If d divides num, so does num / d, and one of the two is at most the square root of num. Scanning d up to sqrt(num) finds every pair, and only a perfect square has a d that pairs with itself.

Each pair adds two divisors, or one for the square root. As soon as the count goes past four, the number cannot qualify, so the scan can stop early.

Numbers that do qualify are of the form p * q for distinct primes or p^3, but the pair scan finds them without needing that fact.

Approach: Divisor pairs up to the square root

  1. Set total = 0.
  2. For each num, set count = 0 and div_sum = 0.
  3. For d = 1, 2, ... while d * d <= num: if num % d == 0, add 1 to count and d to div_sum when d == num / d, otherwise add 2 and d + num / d. Break once count > 4.
  4. If count == 4, add div_sum to total.
  5. Return total.

Step-by-step example

nums = [21,4,7]
  1. num = 21: d = 1 gives the pair (1, 21), count 2. d = 3 gives (3, 7), count 4. d = 4 has 16 <= 21 but does not divide, and d = 5 stops the loop. Exactly four, so total = 1 + 21 + 3 + 7 = 32.
  2. num = 4: d = 1 gives (1, 4), count 2. d = 2 is the square root, count 3. Not four, skip.
  3. num = 7: d = 1 gives (1, 7), count 2. d = 2 and up exceed the square root. Not four, skip.
  4. Return 32.

Code: Python, Java, C++

1class Solution:
2    def sumFourDivisors(self, nums: List[int]) -> int:
3        total = 0
4        for num in nums:
5            count, div_sum = 0, 0
6            d = 1
7            while d * d <= num:
8                if num % d == 0:
9                    other = num // d
10                    count += 1 if d == other else 2
11                    div_sum += d if d == other else d + other
12                    if count > 4:
13                        break
14                d += 1
15            if count == 4:
16                total += div_sum
17        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * sqrt(M))

Each of the n numbers is scanned up to the square root of its value M, and many stop early.

Space

O(1)

Only a few counters are kept per number.

Other approaches

Prime factor form (time O(M log log M + n * sqrt(M)), space O(M))

A number has exactly four divisors when it is p^3 or p * q for distinct primes p and q. Sieve primes up to 10^5, then test each number against those two forms.

Divisor count sieve (time O(M log M + n), space O(M))

For every d up to the maximum value, add d to the sum and 1 to the count of each multiple of d. Then answer each number by lookup. Fast for many queries but uses O(M) memory and O(M log M) setup.

Common mistakes

  • Counting the square root twice. For num = 4 the pair (2, 2) is one divisor, not two.
  • Looping d up to num instead of sqrt(num), which is far too slow for large inputs.
  • Adding the sum before the scan is finished. A number can reach four divisors and then find a fifth later.
  • Breaking out of the outer loop instead of the inner one when the count passes four.

Frequently asked questions

Which numbers have exactly four divisors?

Products of two distinct primes, like 21 = 3 * 7, with divisors 1, p, q, pq, and cubes of a prime, like 8 = 2^3, with divisors 1, 2, 4, 8.

Why is stopping at count > 4 safe?

The count only grows as d increases, so once it is above four the number can never end with exactly four divisors.

Can the total overflow a 32-bit integer?

With up to 10^4 numbers below 10^5 the true worst case stays under 2^31 for this problem, so LeetCode uses a 32-bit return type.