- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- while n mod i is same as 0, do
- if n > 2, then
- insert n at the end of res

- return res

Let us see the following implementation to get better understanding −

## Example

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]

- Related Articles
- Python Program for Efficient program to print all prime factors of a given number
- C Program for efficiently print all prime factors of a given number?
- Find all prime factors of a number - JavaScript
- Product of unique prime factors of a number in Python Program
- Java Program to find Product of unique prime factors of a number
- How to find prime factors of a number in R?
- Python Program for Product of unique prime factors of a number
- C/C++ Program to find Product of unique prime factors of a number?
- C/C++ Program to find the Product of unique prime factors of a number?
- Program to find squared elements list in sorted order in Python
- Find all the prime factors of 1729 and arrange them in ascending order. Now state the relation, if any; between two consecutive prime factors.
- Find sum of even factors of a number in Python Program
- Program to find the sum of all digits of given number in Python
- Prime factors of a big number in C++
- Different Methods to find Prime Number in Python Program

Advertisements