Created
January 4, 2026 19:40
-
-
Save tatsuyax25/d1840e990548eb05a9de3891de59a3fb to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var sumFourDivisors = function(nums) { | |
| // Helper: return the sum of divisors of n if it has exactly 4 divisors. | |
| // Otherwise return 0. | |
| function sumIfFourDivisors(n) { | |
| let count = 0; // how many divisors we've found | |
| let sum = 0; // sum of those divisors | |
| // Check all possible divisors from 1 up to sqrt(n) | |
| for (let d = 1; d * d <= n; d++) { | |
| if (n % d === 0) { | |
| let other = n / d; | |
| if (d === other) { | |
| // d is the square root, counts as one divisor | |
| count += 1; | |
| sum += d; | |
| } else { | |
| // d and n/d are two distinct divisors | |
| count += 2; | |
| sum += d + other; | |
| } | |
| // If we already have more than 4 divisors, we can stop early | |
| if (count > 4) { | |
| return 0; | |
| } | |
| } | |
| } | |
| // Only numbers with exactly 4 divisors are valid | |
| return count === 4 ? sum : 0; | |
| } | |
| let total = 0; | |
| // For each number in the array, add the contribution | |
| for (let num of nums) { | |
| total += sumIfFourDivisors(num); | |
| } | |
| return total; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment