How to compute all the factors of a given number in Python

The following python program computes and prints all the positive factors of a given input number.


# This function returns a list containing all the factors of a ginven parameters n
def getFactors(n):
    # Create an empty list for factors

    # Loop over all factors
    for i in range(1, n + 1):
        if n % i == 0:

    # Return the list of factors
    return factors

# Call the function with a given value
print (getFactors(256))

Here is how the above program works:


[1, 2, 4, 8, 16, 32, 64, 128, 256]

Prime number

It becomes easy to test if a given integer is a prime number:

if len(getFactors(42))==2:
    print ('Prime number')
    print ('Not a prime number')

See also

Last update : 04/13/2019