Python Program - Find All Factors of a Given Number


Find All Factors of a Given Number

In this program, we take a number in n, and find all the factors of this number.

Input

n where n>0

Program

We write findFactors() function that takes n as parameter, and returns a list of all the factors for given number.

Python Program

def findFactors(n):
    factors = []

    for i in range(1,n+1):
        #check if i is a factor
        if n % i == 0:
            factors.append(i)

    return factors


n = 10
result = findFactors(n)
print(result)

Output #1

[1, 2, 5, 10]

Output #2

Enter n : 512
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Program for Efficiency

We can make the above program more efficient. How? If i is a factor of n, then n/i is also a factor. We can take advantage of this and limit our iterations to n/i instead of n.

Python Program

def findFactors(n):
    factors = []

    i = 1
    while i < (n / i):
        #check if i is a factor
        if n % i == 0:
            factors.append(i)
            #if i is a factor, then n/i is also a factor
            factors.append(int(n/i))
        i += 1
    
    factors.sort()
    return factors


n = 10
result = findFactors(n)
print(result)

Output

[1, 2, 5, 10]

Summary

In this tutorial of Python General Programs, you learned how to find all the factors of a given number.