Python Program to print all prime factors of a number

In this simple python program, we need to check for prime factors of a number. It is an intermediate-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is a prime factor?

In this simple python program, we need to print the prime factors of the number. So first find factors of the given number, and then check if there are any prime numbers in that.

For example, let us take an integer 25

  • Calculate the factors of 25, which are 1, 5
  • There we check for any prime number, and 5 is a prime number.
  • So 5 is a prime factor of 5.

A prime number is a number that has only two factors, which are the 1 and that number itself; please refer to the prime number python program for more details.

NOTE: Number 1 is not a Prime number

How to check for prime factors of a number in python?

To apply this logic in the python programming language, we open a while loop from 1 to number after accepting the number from the user. Then find all divisors of the number using the Mod (%) operator inside an if condition in python. After finding a divisor, check if this divisor is prime? for that use another while loop and find each factor of the divisor. If the divisor has only two factors, then it is a prime divisor so print the divisor, and again iterate the outer loop to find the next divisor.

ALGORITHM

STEP 1: Accept input from the user using the input function in python programming.

STEP 2: Initialize a variable 'i =1' and open a while loop from 1 to the input number.

STEP 3: Initialize the variable k = 0.

STEP 4: Using an if condition checks the number mod i is zero to get the divisor and initialize j =1.

STEP 5: Open the while loop from 1 to the divisor to check if the divisor is prime or not.

STEP 6: Now check the divisor has any factors using if condition and mod operator.

STEP 7: If any factors are found, increment another variable k by 1.

STEP 8: Increment j by 1 and check the value of k; if the k == 2, then print that divisor is prime.

STEP 9: Increment the i by 1 in python programming.

Python Source Code

                                          n=int(input("Enter an integer:"))
print("Prime Factors are:")
i=1
while(i<=n):
    k=0
    if(n%i==0):
        j=1
        while(j<=i):
            if(i%j==0):
                k=k+1
            j=j+1
        if(k==2):
            print(i)
    i=i+1
                                      

OUTPUT

Enter an integer:24
Prime Factors are:
2
3