[Python] fastest way to produce a list of all divisors of a number

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Given a number n, I want to generate a sorted list of all the unique divisors of n (with no duplications). Solving this problem is really straight forward, but what I'm interested in is the efficiency. What is the fastest way to do it?

    Here is one way, with pure python:

    def get_divisors(n):
    """
    :param n: positive integer.
    :return: list of all different divisors of n.
    """
    if n <= 0:
    return []
    divisors = [1, n]
    for div in range(1, int(n ** 0.5 + 1)):
    if n % div == 0:
    divisors.extend([n // div, div])
    return sorted(list(set(divisors)))



    Any suggestions on how to optimize this? Numpy and other optimized libraries are welcome.

    Continue reading...

Compartilhe esta Página