Categories
Python Answers

How to find all the factors of a number in Python?

Spread the love

Sometimes, we want to find all the factors of a number in Python.

In this article, we’ll look at how to find all the factors of a number in Python.

How to find all the factors of a number in Python?

To find all the factors of a number in Python, we can use the functools module.

For instance, we write:

from functools import reduce


def factors(n):
    return set(
        reduce(list.__add__, ([i, n // i]
                              for i in range(1,
                                             int(n**0.5) + 1) if n % i == 0)))


print(factors(50))

We define the factors function which takes the number n to get the factors from.

In the function, we call reduce with list.__add__ as the function to call to to add the factors into a list.

Then we compute the factors with ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0) to compute the factors by getting all the numbers i that can divide n evenly.

Finally, we call set to remove the duplicates from the list returned by reduce.

Therefore, we should see {1, 2, 5, 10, 50, 25} from the print output.

Conclusion

To find all the factors of a number in Python, we can use the functools module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *