Program to find all prime factors of a given number in sorted order in Python


Suppose we have a number n greater than 1, we have to find all of its prime factors and return them in sorted sequence. We can write out a number as a product of prime numbers, they are its prime factors. And the same prime factor may occur more than once.

So, if the input is like 42, then the output will be [2, 3, 7].

To solve this, we will follow these steps −

  • res:= a new list
  • while n mod 2 is same as 0, do
    • insert 2 at the end of res
    • n := quotient of n/2
  • for i in range 3 to (square root of n), increase in step 2
    • while n mod i is same as 0, do
      • insert i at the end of res
      • n := quotient of n/i
  • if n > 2, then
    • insert n at the end of res
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      res=[]
      while n%2==0:
         res.append(2)
         n//=2
      for i in range(3,int(n**.5)+1,2):
         while n%i==0:
            res.append(i)
            n//=i
      if n>2:
         res.append(n)
      return res
ob = Solution()
print(ob.solve(42))

Input

42

Output

[2, 3, 7]

Updated on: 07-Oct-2020

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements