Sum of Divisors - FreeCodeCamp #138 Daily Challenge

2 min

Problem Statement: Sum of Divisors

Given a positive integer nn, return the sum of all its divisors (integers that divide nn with no remainder).

For example, for n=6n = 6, the divisors are 1,2,3,61, 2, 3, 6 and the sum is 1212.

Examples:

  • sumOfDivisors(6)1212
  • sumOfDivisors(13)1414
  • sumOfDivisors(28)5656
  • sumOfDivisors(84)224224
  • sumOfDivisors(549)806806
  • sumOfDivisors(9348)2352023520

Analysis and Test Cases

To solve the problem, we just need to identify all divisors of nn (that is, all ii such that n%i=0n \% i = 0) and sum them. Here are some cases:

nDivisorsSum
61, 2, 3, 612
131, 1314
281, 2, 4, 7, 14, 2856
841, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84224
5491, 3, 9, 61, 183, 549806
93481, 2, 3, 4, 6, 12, 13, 26, 39, 52, 78, 156, 59, 118, 177, 236, 354, 708, 779, 1558, 2337, 3116, 4674, 934823520

These examples cover small, prime, composite, and large values to validate efficiency.

Solution and Explanation

Strategy

We use a direct approach: iterate from 11 to nn and sum the values that divide nn 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: O(n)O(n) (one iteration per number up to nn).
  • Space: O(1)O(1) (only scalar variables).

Edge Cases and Considerations

  • If n=1n = 1, the only divisor is 11 (the function should return 11).
  • The statement assumes nn is positive.
  • For primes, the sum is n+1n + 1.
  • Negatives and zero are not considered.

Reflections and Learnings

  • The modulo operator is key to identifying divisors.
  • For large nn, you can optimize by iterating up to n\sqrt{n} and summing both divisors, achieving O(n)O(\sqrt{n}).
  • The current version is didactic and clear for beginners.

Resources