Consider the function , which maps a positive integer to the sum of all its positive divisors.
If n = p, where is a prime number, then has exactly two divisors: and . Therefore,
If n = p^a, where is a prime number and a \ge 1, then all divisors of are of the form:
Their sum forms a geometric progression; therefore,
The function is multiplicative, that is, for any pair of coprime integers and , the following equality holds:
Let a positive integer have the following prime factorization
where p_1, p_2, ..., p_k are distinct prime numbers.
Then, using the multiplicativity of and the formula for powers of prime numbers, we obtain:
The above sum can also be written in the following form:
Example
The number n = 239 is prime, that is, it has exactly two positive divisors: and . By the definition of the sum-of-divisors function, we obtain:
Consider the number n = 24. Its prime factorization is:
Since the numbers 2^3 and are coprime, we can apply the multiplicativity of the function :
Let's compute the sum of the divisors of the number n = 24 directly. First, list all positive divisors of :
Adding them together, we obtain:
Notice that all divisors can be grouped in the following way:
Algorithm implementation
Read the input value .
scanf("%lld",&n);Store the value of in the variable .
res = 1;Using the variable , iterate over all prime divisors of the number (according to the problem statement, they do not exceed ). For each such divisor, compute its contribution to the sum of divisors of using the formula derived in the problem analysis.
for (i = 2; i <= 1000; i++)
{
p = i;Let be a prime divisor of n. Find the largest exponent such that i^a divides .
while(n % i == 0)
{
n /= i;
p *= i;
}After the loop terminates, we obtain p = i^{a+1}. Then we multiply the current value of the variable by \frac{i^{a + 1} - 1}{i - 1}.
res *= (p - 1) / (i - 1);
}Print the answer.
printf("%lld\n",res);Java implementation
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
long n = con.nextLong();
long res = 1;
for(int i = 2; i <= 1000; i++)
{
long p = i;
while(n % i == 0)
{
n /= i;
p *= i;
}
res *= (p - 1) / (i - 1);
}
System.out.println(res);
con.close();
}
}Python implementation
Read the input value .
n = int(input())Store the value of in the variable .
res = 1Using the variable , iterate over all prime divisors of the number (according to the problem statement, they do not exceed ). For each such divisor, compute its contribution to the sum of divisors of using the formula derived in the problem analysis.
for i in range (2,1000) :
p = iLet be a prime divisor of n. Find the largest exponent such that i^a divides .
while(n % i == 0) :
n = n // i
p *= iAfter the loop terminates, we obtain p = i^{a+1}. Then we multiply the current value of the variable by \frac{i^{a + 1} - 1}{i - 1}.
res *= (p - 1) // (i - 1) Print the answer.
print(res)