Python Program to find the factors of a number

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

  1. Start
  2. Take input: Prompt the user to enter a number.
  3. Initialize a loop: Iterate through all numbers from 1 to the given number.
  4. Check divisibility: For each number, check if it divides the given number without a remainder (i.e., number % i == 0).
  5. Store the factors: If the number divides evenly, it is a factor.
  6. Display the result: Print all the factors of the number.
  7. 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

  1. Taking input from the user:
    The program uses input() to prompt the user to enter a number, which is then converted to an integer using int().
  2. 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 number i is a factor, and it is appended to the factors list.
  3. Storing and displaying the factors:
    The factors are stored in a list, which is then displayed using the print() function. The join() function is used to format the output by joining the list of factors with commas.

Python

1658

806

Related Articles