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 reduce function.

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)))

to define the factor function that returns the factors by looping from 1 to int(n**0.5) + 1 with a for loop.

And we put the values n that’s evenly divisible by i with

n % i == 0

And we use list.__add__ to add the factors into a list.

Finally, we call set to convert the returned list without the duplicate values by converting the list to a set.

Conclusion

To find all the factors of a number in Python, we can use the reduce function.

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 *