Four Divisors - 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.

Note: A number has exactly four divisors when it is either:

  • The cube of a prime number (p³)
  • The product of two distinct prime numbers (p × q)

Input & Output

Example 1 — Mixed Numbers
$ Input: nums = [21,4,7]
Output: 32
💡 Note: 21 has divisors [1,3,7,21] (4 divisors, sum=32). 4 has divisors [1,2,4] (3 divisors). 7 has divisors [1,7] (2 divisors). Only 21 has exactly 4 divisors.
Example 2 — Multiple Valid Numbers
$ Input: nums = [21,21]
Output: 64
💡 Note: Both instances of 21 have exactly 4 divisors [1,3,7,21] with sum 32. Total: 32 + 32 = 64.
Example 3 — No Valid Numbers
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: 1 has 1 divisor, 2 has 2 divisors, 3 has 2 divisors, 4 has 3 divisors, 5 has 2 divisors. None have exactly 4 divisors.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Four Divisors Problem INPUT Integer Array nums 21 [0] 4 [1] 7 [2] Divisor Analysis: 21: 1, 3, 7, 21 (4 divisors - OK) 3 x 7 = two primes 4: 1, 2, 4 (3 divisors - skip) 7: 1, 7 (2 divisors - skip) ALGORITHM STEPS 1 Count Divisors Iterate 1 to sqrt(n) 2 Check if divisor If n % i == 0, count it 3 Track divisor sum Sum all divisors found 4 Check count == 4 Add sum if exactly 4 Processing 21: i=1: 21%1=0 div: 1, 21 i=3: 21%3=0 div: 3, 7 count = 4 sum = 1+3+7+21 sum = 32 Valid! FINAL RESULT Numbers with 4 divisors: 21 3 x 7 (two primes) Sum of Divisors: 1 + 3 + 7 + 21 = 32 Output: 32 Result confirmed! Key Insight: A number has exactly 4 divisors only in two cases: (1) p^3 where p is prime (divisors: 1, p, p^2, p^3) or (2) p x q where p, q are distinct primes (divisors: 1, p, q, pq). Example: 21 = 3 x 7 has divisors 1, 3, 7, 21. Use sqrt(n) optimization: for each divisor d, n/d is also a divisor. Stop early if count exceeds 4. TutorialsPoint - Four Divisors | Optimized Divisor Counting
Asked in
Google 12 Facebook 8 Amazon 6
12.5K Views
Medium Frequency
~25 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen