Objective
Develop a Python program that displays a number (entered by the user) as a product of its prime factors. For example, 60 = 2 · 2 · 3 · 5
(Hint: it can be easier if the solution is displayed as 60 = 2 · 2 · 3 · 5 · 1)
Example Python Exercise
Show Python Code
# Prompt the user for a number
number = int(input("Enter a number: "))
# Initialize an empty list to store the prime factors
prime_factors = []
# Start with the smallest prime factor (2)
divisor = 2
# Loop to find prime factors
while number > 1:
while number % divisor == 0: # Check if the divisor is a factor
prime_factors.append(divisor) # Add the divisor to the list
number //= divisor # Divide the number by the divisor
divisor += 1 # Move to the next possible divisor
# Display the result as a product of prime factors
print(f"The prime factors of the number are: {' * '.join(map(str, prime_factors))}")
Output
Case 1:
Enter a number: 60
The prime factors of the number are: 2 * 2 * 3 * 5
Case 2:
Enter a number: 100
The prime factors of the number are: 2 * 2 * 5 * 5
Case 3:
Enter a number: 7
The prime factors of the number are: 7
Share this Python Exercise
More Python Programming Exercises of Python Data Types
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
This Python program prompts the user to enter a symbol and determines whether it is an uppercase vowel, a lowercase vowel, a digit, or any other ...
This Python program uses a "for" loop to print the uppercase letters from "B" to "N". By utilizing Python's range() function and specifying the A...
This Python program calculates an approximation for PI using the series expression: pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 ... The program allows t...
This Python program calculates the perimeter, area, and diagonal of a rectangle based on its width and height. The program prompts ...
This Python program prompts the user to enter a number and then displays its equivalent values in both hexadecimal and binary formats. The program conti...
This Python program prompts the user to enter a decimal number and displays its equivalent in binary form. Instead of using the str() function, the prog...