Python Program for Find Sum of Odd Factors of a Number (original) (raw)
Last Updated : 30 Oct, 2025
Given a number n, the task is to find the sum of all its odd factors. Odd factors are the divisors of n that are not divisible by 2. For example:
**Input: n = 30
**Output: 24
Odd divisors -> 1, 3, 5, 15 -> Sum = 24**Input: n = 18
**Output: 13
Odd divisors -> 1, 3, 9 -> Sum = 13
Lets explore different methods to find sum of odd factors of a number in python.
Formula-based Approach
In this method, we use the prime factorization of n and ignore even factors. We repeatedly divide n by 2 to remove all even factors, then calculate the sum of odd divisors using powers of remaining primes.
python `
import math n = 30 res = 1
while n % 2 == 0: n //= 2
for i in range(3, int(math.sqrt(n)) + 1): curr_sum = 1 curr_term = 1 while n % i == 0: n //= i curr_term *= i curr_sum += curr_term res *= curr_sum
if n >= 2: res *= (1 + n)
print(res)
`
**Explanation:
- math.sqrt(n) gives upper limit for checking factors efficiently.
- while n % 2 == 0 removes all even factors from n.
- For each odd divisor i, multiply terms (1 + i + i² + ... ).
- Final product res gives the total odd factor sum.
Optimized Divisor Pairing
Here, we reduce the number of iterations by checking divisors only up to √n. For each divisor i, both i and n/i are considered if they are odd.
Python `
import math n = 30 odd_sum = 0
for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: if i % 2 == 1: odd_sum += i if (n // i) % 2 == 1 and n // i != i: odd_sum += n // i
print(odd_sum)
`
**Explanation:
- math.sqrt(n) limits loop to smallest half of divisors.
- For each divisor i, check both i and its pair n // i.
- Add them only if they are odd and avoids double-counting perfect squares.
Iterative Divisor Check
In this method, we loop through all numbers up to n and add only the odd divisors. It’s easy to understand but slower for large numbers.
Python `
n = 30 odd_sum = 0
for i in range(1, n + 1): if n % i == 0 and i % 2 == 1: odd_sum += i
print(odd_sum)
`
**Explanation:
- Loop from 1 to n to check all divisors.
- n % i == 0 ensures i divides n.
- i % 2 == 1 ensures i is odd.
- Adds only odd divisors to odd_sum.
Using List Comprehension
Here, we use list comprehension to quickly collect all odd divisors and sum them directly. It’s concise and Pythonic but not as efficient as formula-based or paired divisor methods.
Python `
n = 30 odd_sum = sum([i for i in range(1, n + 1) if n % i == 0 and i % 2 == 1]) print(odd_sum)
`
**Explanation:
- [i for i in range(1, n + 1) ...] builds a list of odd divisors.
- sum() adds all elements of that list.
- Simple one-line logic, easy to read for small values of n.
Please refer complete article on Find sum of odd factors of a number for more details!