Python Program for Efficient program to print all prime factors of a given number

In this article, we will learn about an efficient solution to find and print all prime factors of a given number. Prime factors are prime numbers that divide the given number exactly.

Problem statement ? We are given a number, we need to find all the prime factors of a given number.

Algorithm Approach

The efficient solution follows these steps:

  • First, divide the number by 2 as much as possible
  • Then check odd numbers from 3 up to ?n
  • If any remainder exists greater than 2, it's also a prime factor

Example

Here's the efficient implementation to find prime factors ?

import math

def primeFactors(n):
    # Handle even divisibility by 2
    while n % 2 == 0:
        print(2)
        n = n // 2
    
    # n is now odd, check odd factors from 3 to ?n
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        # while i divides n
        while n % i == 0:
            print(i)
            n = n // i
    
    # if n is a prime greater than 2
    if n > 2:
        print(n)

# Test the function
n = 200
print(f"Prime factors of {n}:")
primeFactors(n)

The output of the above code is ?

Prime factors of 200:
2
2
2
5
5

How It Works

Prime Factorization of 200 200 ÷ 2 = 100 100 ÷ 2 = 50 50 ÷ 2 = 25 25 ÷ 3 ? 0 25 ÷ 5 = 5 5 ÷ 5 = 1 Prime Factors: 2 × 2 × 2 × 5 × 5 = 200

Key Points

  • Time Complexity: O(?n) - we only check divisors up to square root
  • Division by 2: Handle even factors separately for efficiency
  • Odd factors only: After removing 2s, only check odd numbers
  • Final check: If remainder > 2, it's the largest prime factor

Alternative Implementation

Here's a version that returns the factors as a list ?

import math

def getPrimeFactors(n):
    factors = []
    
    # Handle factor 2
    while n % 2 == 0:
        factors.append(2)
        n = n // 2
    
    # Handle odd factors
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            factors.append(i)
            n = n // i
    
    # If n is a prime greater than 2
    if n > 2:
        factors.append(n)
    
    return factors

# Test with different numbers
numbers = [12, 15, 29, 100]
for num in numbers:
    factors = getPrimeFactors(num)
    print(f"Prime factors of {num}: {factors}")

The output of the above code is ?

Prime factors of 12: [2, 2, 3]
Prime factors of 15: [3, 5]
Prime factors of 29: [29]
Prime factors of 100: [2, 2, 5, 5]

Conclusion

This efficient algorithm finds prime factors in O(?n) time by first handling factors of 2, then checking odd numbers up to the square root. The approach minimizes unnecessary iterations and handles edge cases properly.

Updated on: 2026-03-25T06:56:59+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements