Skip to content

Instantly share code, notes, and snippets.

@D-Lite
Created January 4, 2026 17:08
Show Gist options
  • Select an option

  • Save D-Lite/e58be851b3079ce1dfaa6fc8bd81011e to your computer and use it in GitHub Desktop.

Select an option

Save D-Lite/e58be851b3079ce1dfaa6fc8bd81011e to your computer and use it in GitHub Desktop.
Jan 4
Initial approach is to follow through with all numbers, ensuring once their divisor is > 4, they are dismissed immediately.
Further check down the line shows we can find the square root of this numbers, and divide from 1 to the √num. If perfect square, we can multiply divisor by 2 then -1 or if not perfect , we can multiply by 2 and add 0.
Some feedbacks received also showed we can use other mathematical derivatives like:
numbers with 4 divisors have unique features:
a. n = p³ (cube of a prime, divisors: 1, p, p², p³) => e.g 8 = 2^3
Divisors: 1, 2, 4, 8 (which is 1, 2¹, 2², 2³)
b. n = p × q => sum of 2 dinstinct prime numbers. => 21 = 3 × 7
Divisors: 1, 3, 7, 21
But the sqrt implementation is the most optimal.
```
use std::collections::HashSet;
impl Solution {
pub fn sum_four_divisors(nums: Vec<i32>) -> i32 {
let mut total_sum = 0;
for num in nums {
if let Some(sum) = Self::find_divisor_sum_if_exactly_four(num) {
total_sum += sum;
}
}
return total_sum;
}
pub fn find_divisor_sum_if_exactly_four(num: i32) -> Option<i32> {
let mut divisor_set = HashSet::new();
let limit = (num as f64).sqrt() as i32;
for i in 1..=limit {
if num % i == 0 {
divisor_set.insert(i);
divisor_set.insert(num / i);
if divisor_set.len() > 4 {
return None;
}
}
}
if divisor_set.len() == 4 {
Some(divisor_set.iter().sum())
} else {
None
}
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment