# Find the Factors of a Number (Solution)

Copied!
Happy Pythoning!

Anonymous

A different approach that uses the square root approach, i added comments for myself, i’m not a match genius so there might be some small errors here and there

``````from math import sqrt

def find_factors(n: int) -> list[int]:
factors = []  # Create a list that will hold all the factors of n

# Calculate the floor of n square root
square_root = int(sqrt(n))  # upper bound limit

# Any number <= to the square root, there exist a factor n/i
# that is >= to the square root of n
i = 1
while i <= square_root:
# check if n is divisible by i
if n % i == 0:

# if n / i is equal to the square root
# we dont add n/i to the the list of factors
# n is a perfect square and n/i == i, this avoids duplication
if n / i == i:
factors.append(i)
else:
# since i is not the square root of n
# we have a distinct factors of i and n/i
factors.extend([i, int(n/i)])
i += 1

# (1, 12) i, n/i
# (2, 6)  i, n/i
# (3, 4)  i, n/i
return sorted(factors)

number = int(input('Enter a positive integer: '))
factors = find_factors(number)

for i in factors:
print('{} is a factor of {}'.format(i, number))
``````

Anonymous

Made a little mistake, i += 1 is nested wrong, it should be outside the if statements and the if statement should be one space less otherwise it would not match with the indentation of i += 1.