Factors of a number are integers that divide the number without leaving any remainder. For example, the factors of 12 are 1, 2, 3, 4, 6, and 12, because dividing 12 by these numbers results in whole numbers, meaning there is no remainder.
In this blog, I provide a Python program to find all the factors of a given number. Since factors of a number always appear in pairs (e.g., the factors of 36 include pairs like 2 and 18, 4 and 9), the program uses this property to minimize the number of iterations needed to find the factors. This optimization reduces execution time, especially for large numbers.
import sys
import math
def find_factors(n):
"""
Find factors of the given number.
since factors appear in pairs, this function uses that to minimize the iterations.
"""
factors = set()
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
factors.add(i)
factors.add(n // i)
return sorted(factors)
def main():
"""
Find factors of a number >0
"""
# provide the number as a command-line argument
args = sys.argv
# check if user provided a value or not
if len(args) < 2:
print("please provide an integer >0 as command-line argument")
else:
num = int(args[1])
if num > 0:
print(f"Factors of {num}: {find_factors(num)}")
else:
print("please provide an integer >0")
if __name__ == "__main__":
main()
To run the code, save it as find_factors.py (or whatever name prefer) and execute it with a number as a command-line argument, as shown below.
python find_factors.py 15
Please let me know in the comments if you find any issues with the code.