Introduction
Prime factorization is the process of determining the prime numbers that multiply together to give the original number.
Every positive integer greater than 1 can be represented as a product of prime numbers. For example, the prime factors of
28 are 2 and 7 because 28 = 2 × 2 × 7. In this program, we will write Python code to find the prime factors of a given integer
number.
Objective
The objective of this program is to identify and print the prime factors of a given integer. We will achieve this by
iteratively dividing the number by the smallest possible prime numbers until the remaining number becomes 1. This will
help in extracting all the prime factors.
Python Code
# Program to find prime factors of a given number def prime_factors(n): # Check for number of 2s that divide n while n % 2 == 0: print(2, end=" ") n = n // 2 # n must be odd at this point, so we can skip one element (i = i +2) for i in range(3, int(n**0.5) + 1, 2): # While i divides n, print i and divide n while n % i == 0: print(i, end=" ") n = n // i # If n is a prime number greater than 2 if n > 2: print(n) # Driver code if __name__ == "__main__": number = int(input("Enter a number to find its prime factors: ")) print(f"Prime factors of {number} are:", end=" ") prime_factors(number)
Explanation of the Program
This Python program starts by defining the prime_factors
function, which takes an integer n
as input
and prints its prime factors. The function first checks if 2 is a factor of the number by dividing n
by 2 in a loop.
This is done until n
is no longer divisible by 2, at which point the program proceeds to check for higher prime factors.
After checking for divisibility by 2, the program moves on to check divisibility by odd numbers starting from 3 up to the square
root of the remaining number. For each odd divisor, the program divides the number as long as it is divisible by that number. This
ensures that we find all prime factors of n
.
Finally, if the remaining n
is greater than 2, it is itself a prime number and is printed. The program ends by calling
the prime_factors
function inside the if __name__ == "__main__":
block, where the user is prompted to
input a number.
How to Run the Program
To run this program, follow these steps:
- Copy the Python code provided above into a new file. You can name the file
prime_factors.py
. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Run the Python program by typing
python prime_factors.py
and press Enter. - The program will ask you to enter a number. After you input a number, the prime factors of that number will be displayed.