How to find all divisors of a number in Python

1 Answer

0 votes
import math

def find_divisors(n):
    """
    Efficiently find all divisors of a number using the sqrt(n) method.

    Explanation:
      - We loop only up to sqrt(n), which reduces the number of iterations.
      - If i divides n, then both i and n//i are divisors.
      - If i == n//i (perfect square), we add it only once.
      - Finally, we sort the list so the divisors appear in ascending order.
    """
    divisors = []
    limit = int(math.sqrt(n))

    for i in range(1, limit + 1):
        if n % i == 0:
            divisors.append(i)          # Add the smaller divisor

            if i != n // i:             # Avoid duplicates for perfect squares
                divisors.append(n // i) # Add the paired divisor

    divisors.sort()
    
    return divisors


# Main program
num = 24  

result = find_divisors(num)
print(f"Divisors of {num}: {result}")


"""
run:

Divisors of 24: [1, 2, 3, 4, 6, 8, 12, 24]

"""

 



answered Jun 30, 2020 by avibootz
edited Jul 1 by avibootz
...