Last Updated: June 7, 2026
Find every number that divides n evenly and add them together. A number i is a divisor of n when n % i equals 0. The list always starts at 1, because 1 divides every integer, and ends at n, because every number divides itself.
Take n = 12. From 1 to 12, the values that divide it cleanly are 1, 2, 3, 4, 6, 12, which sum to 28. The rest, like 5, 7, and 8, leave a remainder and are skipped.
The challenge is finding all the divisors efficiently. The direct method tests every candidate up to n, which is fine for small inputs. With n as large as 10^6, a faster method uses the fact that divisors come in pairs.
n can be as large as 10^6 → A linear scan does up to a million checks, which is acceptable, but a square-root scan does only about a thousand and scales far better.n is always positive → There are no negative or zero edge cases to guard against, so the loop logic stays simple.Walk through every candidate from 1 to n, test each one with the modulo operator, and add the ones where n % i is 0. This is easy to reason about and a solid baseline before optimizing.
sum to 0.i from 1 to n.n % i equals 0, then i is a divisor, so add i to sum.sum.Input:
Walking from 1 to 12, the values where 12 % i equals 0 are 1, 2, 3, 4, 6, 12. Each one gets added to the running total: 1 + 2 + 3 + 4 + 6 + 12. The numbers 5, 7, 8, 9, 10, 11 all leave a remainder, so they are skipped. The final sum is 28.
1 to n, performing one modulo check each time.n is.Divisors come in pairs. If i divides n, then n / i divides n too. For n = 12, 2 pairs with 6, and 3 pairs with 4. One member of each pair is at most the square root of n and the other is at least the square root, so scanning only up to the square root finds both members of every pair.
Loop i while i * i <= n. Whenever i divides n, add both i and its partner n / i. One detail needs care: when n is a perfect square, i equals n / i at the middle, so add that divisor only once to avoid counting it twice.
sum to 0.i starting at 1 while i * i <= n.n % i equals 0, then i is a divisor:i to sum.n / i. If it differs from i, add it to sum as well. If it equals i, skip it so the perfect-square divisor is not double counted.sum.Input:
The loop runs while i * i <= 12, so i goes 1, 2, 3 (since 4 * 4 = 16 exceeds 12). At i = 1, 1 divides 12, so add the pair 1 + 12. At i = 2, 2 divides 12, so add the pair 2 + 6. At i = 3, 3 divides 12, so add the pair 3 + 4. The collected pairs are 1+12, 2+6, 3+4, and together they sum to 28. Because 12 is not a perfect square, every pair has two distinct members, so no value is skipped.
i passes the square root of n, so it runs about sqrt(n) times instead of n times.