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

Prime factorization is the process of breaking down a number into its prime factors. A prime factor is a prime number that divides the given number exactly. For example, the prime factors of 42 are 2, 3, and 7 because 42 = 2 × 3 × 7.

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

Algorithm

To find all prime factors efficiently, we follow these steps:

  • Create an empty result list
  • Handle factor 2 separately (divide by 2 until odd)
  • Check odd numbers from 3 to ?n
  • If any remainder exists greater than 2, it's also a prime factor

Implementation

Here's the complete solution to find all prime factors:

import math

class Solution:
    def solve(self, n):
        factors = []
        
        # Handle factor 2
        while n % 2 == 0:
            factors.append(2)
            n //= 2
        
        # Check odd factors from 3 to sqrt(n)
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            while n % i == 0:
                factors.append(i)
                n //= i
        
        # If n is still greater than 2, it's a prime factor
        if n > 2:
            factors.append(n)
            
        return factors

# Test the solution
ob = Solution()
print(ob.solve(42))
print(ob.solve(100))
print(ob.solve(17))
[2, 3, 7]
[2, 2, 5, 5]
[17]

How It Works

The algorithm works in three phases:

  1. Factor out 2: We first divide by 2 repeatedly to handle all even factors
  2. Check odd factors: We only check odd numbers from 3 to ?n since even factors are already handled
  3. Handle remaining prime: If n > 2 after factorization, it's itself a prime factor

Alternative Simple Approach

Here's a simpler version without using a class:

def prime_factors(n):
    factors = []
    d = 2
    
    while d * d <= n:
        while n % d == 0:
            factors.append(d)
            n //= d
        d += 1
    
    if n > 1:
        factors.append(n)
    
    return factors

# Test with different numbers
print(prime_factors(42))
print(prime_factors(60))
print(prime_factors(13))
[2, 3, 7]
[2, 2, 3, 5]
[13]

Time Complexity

The time complexity is O(?n) because we only check divisors up to the square root of n. The space complexity is O(log n) for storing the prime factors.

Conclusion

Prime factorization efficiently breaks down numbers using trial division up to ?n. The algorithm handles even factors separately, then checks odd divisors to find all prime factors in ascending order.

Updated on: 2026-03-25T11:04:06+05:30

868 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements