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 after finding the given number factors, let us check if there any prime numbers in that. For example, let us take an integer 25, let us calculate the factors of 25, which are 1, 5. There we check for any prime number, and 5 is a prime number.

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 problem for details.

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 check for all divisors of the number using the Mod operator inside an if condition in python. After finding the divisors open a while loop from 1 to the divisor. Check how many divisors the resultant divisor has, using another variable.

If the divisor has only two divisors, then it is a prime divisor so print the divisor again iterate the outer loop to take 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 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("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 : 25

Prime factors are :  5