Prime Factor Program in Python

Get a number x and find the prime factors of x.

Sample Input 1:

24

Sample Output 1:

1<br>

2<br>

3

Note:

1 2 3 4 6 8 12 are the factors of 24. <br>

1, 2 and 3 are the Prime numbers in above factors.


Program or Solution

				
				
					

#Program to Find Prime Factors of Given number n
n = int(input("Enter a Number:")) #get input n
#checks which are the numbers from 1 to n/2 divides n.
#No other after n/2 divides n except n
for i in range(1,n//2+1):
    if n % i == 0: # if divisible then it a factor
        #Check Factor is Prime
        for j in range(2,i//2+1):
            if i%j == 0: #if divisible not a prime
                break
        else:
            print(i) #print the prime factor

Program Explanation

input() gets the value of n from users as string, and int() coverts the same to integer. 

The following for loop iterates from i = 1 to at n/2, in each iteration it checks whether the n is divisible by i.

No other number after n/2 divides n except n.

if i divides n then check whether i is prime or not. if i is prime print i.


Tech Events

Hackathon