Python program for Find sum of odd factors of a number

By IncludeHelp Last updated : February 17, 2024

Problem statement

Given an integer number, write a Python program to find the sum of odd factors of the given number.

Consider the below example with sample values:

Input:
num = 120

Odd factors of 120 are: 1, 3, 5, 15

Output:
Sum of all odd factors is: 1 + 3 + 5 + 15 = 24
Input:
num = 55

Odd factors of 55are: 1, 5, 11, 55

Output:
Sum of all odd factors is: 1 + 5 + 11 + 55 = 24

Finding of sum of odd factors of a number

To find the sum of odd factors, find the factors of a number and ignore the even factors with their powers. To remove all even factors, divide the given number if it is divisible by 2 repeatedly and use another loop to get and find the sum of odd factors.

# Import math module
import math

# Function that returns the sum of odd factors
# of the given number
def SumOddFactors(num):
    # Traversing through all
    # prime factors.
    result = 1

    # Ignoring even factors
    while num % 2 == 0:
        num = num // 2

    for i in range(3, int(math.sqrt(num) + 1)):
        count = 0
        curr_sum = 1
        curr_term = 1
        while num % i == 0:
            count += 1

            num = num // i
            curr_term *= i
            curr_sum += curr_term

        result *= curr_sum

    # For prime number
    if num >= 2:
        result *= 1 + num

    return result

# The main code
num = 120
print(SumOddFactors(num))

num = 55
print(SumOddFactors(num))

Output

The output of the above code is:

24
72

To understand the above program, you should have the basic knowledge of the following Python topics:

 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.