Let’s write a Python program to generate factors of a number.
What are factors of a number?
The factors of a number are those numbers which can divide the given number exactly. A number when divided by its factor yields a zero remainder. Some examples are given below.
- The factors of the number 10 are 1, 2, 5 and 10.
- The factors of the number 20 are 1, 2, 4, 5, 10 and 20.
Each number has atleast two factors, 1 and the number itself.
How to generate factors of a number?
To generate the factors of a number, we create a loop which starts with 1 and iterates upto the given number N. The number in each iteration is checked whether it is a factor by dividing the number N with the number. If division yields a zero remainder, the number is a factor.
Python code (to generate factors of a number)
#code to generate factors of a number
n = int(input("Enter a number "))
print("The factors are")
i = 1
while i<=n:
if n%i==0:
print(i)
i=i+1
Python code (to generate factors using function)
The code to generate factors of a number can be written using a function, which returns the factors as a Python list.
#Function to generate factors of a number
def getFactors(n):
factors = []
i = 1
while i<=n:
if n%i==0:
factors.append(i)
i=i+1
return factors
#code to test the above function
n = int(input("Enter a number "))
print("The factors are", getFactors(n))