Sum of Divisors - FreeCodeCamp #138 Daily Challenge
2 min
Problem Statement: Sum of Divisors
Given a positive integer , return the sum of all its divisors (integers that divide with no remainder).
For example, for , the divisors are and the sum is .
Examples:
sumOfDivisors(6)→sumOfDivisors(13)→sumOfDivisors(28)→sumOfDivisors(84)→sumOfDivisors(549)→sumOfDivisors(9348)→
Analysis and Test Cases
To solve the problem, we just need to identify all divisors of (that is, all such that ) and sum them. Here are some cases:
| n | Divisors | Sum |
|---|---|---|
| 6 | 1, 2, 3, 6 | 12 |
| 13 | 1, 13 | 14 |
| 28 | 1, 2, 4, 7, 14, 28 | 56 |
| 84 | 1, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84 | 224 |
| 549 | 1, 3, 9, 61, 183, 549 | 806 |
| 9348 | 1, 2, 3, 4, 6, 12, 13, 26, 39, 52, 78, 156, 59, 118, 177, 236, 354, 708, 779, 1558, 2337, 3116, 4674, 9348 | 23520 |
These examples cover small, prime, composite, and large values to validate efficiency.
Solution and Explanation
Strategy
We use a direct approach: iterate from to and sum the values that divide exactly. It’s simple, clear, and sufficient for the problem’s input sizes.
Flowchart
flowchart TD
A["Input: n"] --> B["Initialize sum = 0"]
B --> C["Iterate i = 1 to n"]
C --> D{"n % i == 0?"}
D -- Yes --> E["sum += i"]
D -- No --> C
E --> C
C --> F["End of loop"]
F --> G["Return sum"]
JavaScript Code
function sumOfDivisors(n) {
let sum = 0
for (let i = 1; i <= n; i++) {
if (n % i === 0)
sum += i
}
return sum
}Complexity
- Time: (one iteration per number up to ).
- Space: (only scalar variables).
Edge Cases and Considerations
- If , the only divisor is (the function should return ).
- The statement assumes is positive.
- For primes, the sum is .
- Negatives and zero are not considered.
Reflections and Learnings
- The modulo operator is key to identifying divisors.
- For large , you can optimize by iterating up to and summing both divisors, achieving .
- The current version is didactic and clear for beginners.