Write a Python program to find all the factors of a given number. A factor of a number is a whole number that divides the given number completely (without leaving a remainder).
Input-Output Examples
plaintext
Example 1:
Input: Enter a number: 12
Output: The factors of 12 are: 1, 2, 3, 4, 6, 12
Example 2:
Input: Enter a number: 15
Output: The factors of 15 are: 1, 3, 5, 15
Algorithm to find the factors of a number
- Start
- Take input: Prompt the user to enter a number.
- Initialize a loop: Iterate through all numbers from 1 to the given number.
- Check divisibility: For each number, check if it divides the given number without a remainder (i.e.,
number % i == 0
). - Store the factors: If the number divides evenly, it is a factor.
- Display the result: Print all the factors of the number.
- End
Python Program to find the factors of a number
python
# Python program to find the factors of a number
# Take input from the user
num = int(input("Enter a number: "))
# Initialize an empty list to store factors
factors = []
# Loop through 1 to the number to find its factors
for i in range(1, num + 1):
if num % i == 0: # If the number divides evenly, it's a factor
factors.append(i)
# Display the factors
print(f"The factors of {num} are: {', '.join(map(str, factors))}")
Code Explanation
- Taking input from the user:
The program usesinput()
to prompt the user to enter a number, which is then converted to an integer usingint()
. - Finding the factors:
The program initializes a loop from 1 to the given number (num
). For each number in this range, it checks if the number divides the input number evenly (i.e.,num % i == 0
). If so, the numberi
is a factor, and it is appended to thefactors
list. - Storing and displaying the factors:
The factors are stored in a list, which is then displayed using theprint()
function. Thejoin()
function is used to format the output by joining the list of factors with commas.