Print Prime Factors of A Number in Python

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we find prime factors numbers, seems too easy right!. So let’s quickly find out how to Print Prime Factors Of A Number in Python.

With the help of this program, you will be able to find the root square of integers. Practicing these types of questions also helps to get an upper edge in Competitive Programming.

 

What’s The Approach?

 

  • We know that for each number there are unique prime factors, i.e unique set of prime numbers multiplied together give a different output. The most important aspect of maintaining this unique property of prime factorizations is that the number one, 1, be categorized as neither prime nor composite.

 

  • Let us consider n be the integer we have to print prime factors of. So to do so firstly, we’ll divide n by 2 and print it till it’s divisible by 2.

 

  • After the above instruction n will become odd, so now we’ll iterate a new loop starting from 3 till the square root of n with an increment of 2. In this same loop while i divides n, print i, and divide n by i 

 

  • Finally, if n is a prime number greater than 2 we’ll simply print n. Till this step, we’ll have all the possible prime factors of input number n.

 

Also Read: Print Cube Root of A Number in Python 

 

Python Program To Print Prime Factors of A Number

 

Input:

 

 n = 315

 

Output:

 

3 3 5 7

 

# Python program to print prime factors

import math

# A function to print all prime factors of
# a given number n
def primeFactors(n):
    
    # Print the number of two's that divide n
    while n % 2 == 0:
        print 2,
        n = n / 2
        
    # n must be odd at this point
    # so a skip of 2 ( i = i + 2) can be used
    for i in range(3, int(math.sqrt(n))+1, 2):
        
        # while i divides n, print i ad divide n
        while n % i == 0:
            print i,
            n = n / i
            
    # Condition if n is a prime
    # number greater than 2
    if n > 2:
        print n
        
# Driver Program to test above function

n = 315
primeFactors(n)

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *