Four Divisors
MediumApproaches
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n√m) |
| Space | O(1) | O(1) |
Intuition
The optimal approach leverages the fact that a number can only have exactly four divisors in specific cases: either it is the product of two distinct primes or a cube of a prime. This allows us to check divisors only up to the square root of each number, significantly reducing the number of checks needed.
Algorithm
3 steps- 1Step 1: Initialize a variable to hold the total sum of divisors.
- 2Step 2: For each number in the input array, check for divisors only up to the square root of the number.
- 3Step 3: Count the divisors. If exactly four are found, sum them up.
1# Full working Python code
2
3def sum_of_four_divisors(nums):
4 total_sum = 0
5 for num in nums:
6 divisors = []
7 for i in range(1, int(num**0.5) + 1):
8 if num % i == 0:
9 divisors.append(i)
10 if i != num // i:
11 divisors.append(num // i)
12 if len(divisors) == 4:
13 total_sum += sum(divisors)
14 return total_sum
15
16# Example usage
17print(sum_of_four_divisors([21, 4, 7])) # Output: 32Complexity note: The time complexity is O(n√m) where n is the number of elements in the array and m is the maximum value in the array. We only check up to the square root of each number for divisors, which reduces the number of checks significantly. The space complexity is O(1) since we are using a constant amount of space.
- 1A number has exactly four divisors if it is the product of two distinct primes or a cube of a prime.
- 2Finding divisors only up to the square root of a number significantly reduces the number of iterations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.