Is there a formula to calculate the sum of all proper divisors of a number?

If the prime factorization of $n$ is $$n=\prod_k p_k^{a_k},$$ where the $p_k$ are the distinct prime factors and the $a_k$ are the positive integer exponents, the sum of all the positive integer factors is $$\prod_k\left(\sum_{i=0}^{a_k}p_k^i\right).$$

For example, the sum of all of the factors of $120=2^3\cdot3\cdot5$ is $$(1+2+2^2+2^3)(1+3)(1+5)=15\cdot4\cdot6=360.$$

For proper factors, subtract $n$ from this sum. This may or may not be faster, depending on the number and how you'd get the prime factorization, but this is the typical technique for high school contest problems of this sort.


Just because it is interesting:

There is actually a (less known) recursive formula for calculating $\sigma(n)$, the sum of the divisors of $n$.

$$\sigma(n) = \sigma(n-1) + \sigma(n-2) - \sigma(n-5) - \sigma(n-7) + \sigma(n-12) +\sigma(n-15) + ..$$ Here $1,2,5,7,...$ is the sequence of generalized pentagonal numbers $\frac{3n^2-n}{2}$ for $n = 1,-1,2,-2,...$ and the signs are repetitions of $1,1,-1,-1$. The summation continues until you try to calculate $\sigma$ of something negative. However, if $\sigma(0)$ occurs in the summation (this happens precisely when $n$ is a generalized pentagonal number), it should be replaced by $n$ itself. In other words $$ \sigma(n) = \sum_{i\in \mathbb Z_0} (-1)^{i+1}\left( \sigma(n - \tfrac{3i^2-i}{2}) + \delta(n,\tfrac{3i^2-i}{2})n \right), $$ where we set $\sigma(i) = 0$ for $i\leq 0$ and $\delta(\cdot,\cdot)$ is the Kronecker delta.

Note that calculating $\sigma(n)$ requires $\sigma(n-1)$ already, therefore its complexity is at least $\mathcal O(n)$, which makes it kind of useless for practical purposes. Note however the lack of reference to divisibility in this formula, which makes it a bit miraculous and therefore worth mentioning.

Here's a reference to the Euler's paper from 1751.


Here's a very simple formula:

$$\sum_{i=1}^n \; i\mathbin{\cdot}((\mathop{\text{sgn}}(n/i-\lfloor n/i\rfloor)+1)\mathbin{\text{mod}}2)$$

(for the sake of brevity, one can write $\mathop{\text{frac}}(n/i)$ instead of $n/i-\lfloor n/i\rfloor$).

This is a way to get the function $\text{sigma}(n)$, which generates OEIS's series A000203.

What you want is the function that generates A001065, whose formula is a slight modification of the one above (and with half its computational burden):

$$\sum_{i=1}^{n/2} \; i\mathbin{\cdot}((\mathop{\text{sgn}}(n/i-\lfloor n/i\rfloor)+1)\mathbin{\text{mod}}2)$$

That's it. Straight and easy.