# Codingame Solution: Sum of divisors

Original Problem

You have to print the sum of divisors of all the numbers from $$1$$ to $$n$$. It's superfast when you know the trick but you have to find it. For example if $$n=4$$, lets define $$d(n)$$ the set of the divisors of n:

• d(1)={1}
• d(2)={1,2}
• d(3)={1,3}
• d(4)={1,2,4}

And their sum is $$1+1+2+1+3+1+2+4=15$$. Look carefully at the divisors to find the trick.

I solved this problem already and derived the solution here. Implementing the function in JavaScript is pretty straightforward then:

const n = +readline();
let s = n * n;
for (let i = 1; i <= n; i++) {
s-= n % i;
}
print(s);

« Back to problem overview