Python Program for Number of elements with odd factors in the given range

In this article, we will learn how to find the number of elements with odd factors in a given range. This problem is based on the mathematical property that only perfect squares have an odd number of factors.

Problem statement ? We are given a range [n, m], and we need to find how many numbers in this range have an odd number of factors.

Understanding the Concept

The key insight is that only perfect squares have an odd number of factors. This is because factors usually come in pairs (if d divides n, then n/d also divides n), except when d = n/d, which happens only for perfect squares.

Factor Pairs Visualization Number 12: Factors: 1, 2, 3, 4, 6, 12 Pairs: (1,12), (2,6), (3,4) Total factors: 6 (even) Number 16 (Perfect Square): Factors: 1, 2, 4, 8, 16 Pairs: (1,16), (2,8), (4,4) Total factors: 5 (odd) Perfect Squares have odd factors

Algorithm

To count numbers with odd factors in range [n, m], we need to count perfect squares in this range. The formula is:

count = floor(?m) ? floor(?(n?1))

Example

Let's implement the solution to count perfect squares in a given range ?

import math

def count_odd_factors(n, m):
    """Count numbers with odd factors in range [n, m]"""
    return int(math.sqrt(m)) - int(math.sqrt(n - 1))

# Example 1: Range [25, 400]
n = 25
m = 400
result = count_odd_factors(n, m)
print(f"Numbers with odd factors in range [{n}, {m}]: {result}")

# Example 2: Range [1, 100] 
n2 = 1
m2 = 100
result2 = count_odd_factors(n2, m2)
print(f"Numbers with odd factors in range [{n2}, {m2}]: {result2}")
Numbers with odd factors in range [25, 400]: 16
Numbers with odd factors in range [1, 100]: 10

How It Works

For range [25, 400]:

  • ?400 = 20, so perfect squares ? 400 are 1², 2², ..., 20²
  • ?24 = 4.89, so perfect squares ? 24 are 1², 2², 3², 4²
  • Perfect squares in [25, 400]: 5², 6², ..., 20² = 16 numbers

Verification

Let's verify by listing the perfect squares in range [25, 400] ?

def verify_perfect_squares(n, m):
    """List all perfect squares in range [n, m]"""
    squares = []
    i = 1
    while i * i <= m:
        if i * i >= n:
            squares.append(i * i)
        i += 1
    return squares

# Verify for range [25, 400]
squares = verify_perfect_squares(25, 400)
print(f"Perfect squares in [25, 400]: {squares}")
print(f"Count: {len(squares)}")
Perfect squares in [25, 400]: [25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
Count: 16

Conclusion

To find numbers with odd factors in a range, we count perfect squares using the formula floor(?m) ? floor(?(n?1)). This efficient O(1) solution leverages the mathematical property that only perfect squares have an odd number of factors.

Updated on: 2026-03-25T06:58:13+05:30

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements