Python program to find the sum of the even divisors of a number

Hello everyone, in this Python tutorial, we are going to write a python program to find the sum of the even divisors of a number. Suppose we have a number as 12. Its divisors are 1, 2, 3, 4, 6, 12. The even divisors are 2, 4, 6, 12 and their sum is 24 (2+4+6+12). Let’s have a look at steps we need to follow to write a Python program to find such a sum.

Find the sum of the even divisors of a number in Python

Let’s say our input number is n and its prime factors are p1, p2, …pk. Let a1, a2, …ak be the highest powers of corresponding prime factor. Now we can represent n as below:

n= p1^a1 * p2^a2 * ....pk^ak

We can easily infer from the above that the sum of all the divisors is :

sum of all factors=
(1 + p1 + p1^2 + ...p1^a1) *
(1 + p2 + p2^2 + ...p2^a2) *
.......................... *
(1 + pk + pk^2 + ...pk^ak)

If the number is odd, there will be no even divisors. Hence the sum will be zero. If the number has 2 as one of its prime factors, then the sum can be written as:

sum of all factors= 
(1 + 2 + 2^2 + ...2^a1) * 
(1 + p2 + p2^2 + ...p2^a2) * 
.......................... * 
(1 + pk + pk^2 + ...pk^ak)

Now in order to find the sum of even divisors we need to include only the cases when there is 2 in the factor. Therefore we exclude 1 (2^0) from the above from the second and the sum becomes:

sum of even factors= 
(2 + 2^2 + ...2^a1) * 
(1 + p2 + p2^2 + ...p2^a2) * 
.......................... * 
(1 + pk + pk^2 + ...pk^ak)

Let’s understand the above equation with an example.

Let’s say we have n=12.

The prime factors of n are 2, 3 and we can represent it as 2^2 * 3^1.

Now the sum of even divisors is (2 + 2^2) (1 + 3) = 24.

We can use property of Geometric Progression to find the sum (1 + p + p^2 + …p^a) and (2 + 2^2 + …2^a).

1 + p + p^2 + ...p^a = 1 (p^(a+1) - 1)/(p - 1) = (p^(a+1) - 1)/(p - 1)

Now we will implement it with an example program in Python. See the code.

def EvenDivisorsSum(n):
    
    if n%2 != 0:
        return 0
    if n == 2:
        return 2
    result = 1
    lim = n
    for i in range(2, lim):
        a = 0
        sum_i = 0
        while(n % i == 0):
            n = n // i
            a = a + 1
        sum_i = (i**(a+1)-1)/(i-1)
        if(i==2):
            sum_i = sum_i - 1
        result = result * sum_i
    return result
    
        
        
print(EvenDivisorsSum(30))

The output of the above code is:

48.0

Thank you.

Also, read: Sum of all the factors of a number in Python

Leave a Reply

Your email address will not be published. Required fields are marked *