Creating a python program to print the factors of a number is another good exercise to keep practicing loops in any programming language.
If you divide a number by a second number and you get as remainder 0, then the second number is a factor of the first one.
For instance, 2 is a factor of 10, because 10 divided by 2, gives as remainder 0.
Let’s see the general approach.
A general approach to finding the factors of a number
As I stated at the beginning, this is a good example to practice loops.
So, we need a loop to check all possible numbers that can be factors.
We know from mathematics, that if a number doesn’t have divisors (factors) from 2 to the square root of the number, then the number is prime. Consequently, prime numbers have only two factors, 1 and the number itself.
Also, if a number has a factor between 2 and the square root of the number, will have another factor between the square root of the number and the number itself.
Let’s see this example:
- The number is 16.
- The square root of 16 is 4.
- 2 is a factor because 16 divided by 2 gives as remainder 0.
- But 8 is also a factor because 16 divided by 2 gives 8 as a result. Therefore, if you divide 16 by 8, you get 2 as a result, and 0 as a remainder.
Now we know that the loop to look for factors can be from 2 to the square root of the number.
Every time we find a factor, the result of the division is another factor.
At the end (or the beginning) we can add 1 and the number to the list of factors.
That’s it! That is our general approach to finding the factors of a given number.
Let’s see the python code.
Python program to print the factors of a number
def factors(n):
f = [1,n]
square_root = int(n**0.5) + 1
for i in range(2, square_root):
if n % i == 0:
f.append(i)
f.append(int(n/i))
f.sort()
return f
From the code above, see the following parts of the general strategy stated above:
- We add 1 and the number to the list of factors
- The loop goes from 2 to the square root of the number. In this case, it is plus 1 because of the way that a loop works in Python.
- If the remainder is 0, we found 1 factor.
- We add the other factor that is between the square root and the number by adding the result of the division.
- Finally, we sort the list. This step is optional.
Notice that this code will work only for positive numbers. Because the square root of a negative number gives you a complex number. Also, I only considered the factors that are greater than 0.
You can extend the code to work for negative numbers also, by calculating the square root of the number times -1 if it is negative.
You can also add the negative numbers as factors.
As usual, you can test the implementation below with the following program.
if __name__=='__main__':
n = int(input('Enter a number greater than 1: '))
if n>1:
print(factors(n))
H@ppy coding!
Other exercises related to loops: