Skip to main content
Back to problems
#1390
Medium Algorithms

Four divisors

Array Math
56.6% acceptance
Feb 25, 2026
887
222
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn sum_four_divisors(nums: Vec<i32>) -> i32 {
    let mut total = 0;
    for n in nums {
      let mut divs = vec![1, n];
      let mut i = 2;
      while i * i <= n {
        if n % i == 0 {
          divs.push(i);
          if i != n / i { divs.push(n / i); }
        }
        if divs.len() > 4 { break; }
        i += 1;
      }
      if divs.len() == 4 {
        total += divs.iter().sum::<i32>();
      }
    }
    total
  }
}