Skip to content
Home » Blog » Prime Factorization Algorithm in Python

Prime Factorization Algorithm in Python

What is Prime Factorization

Let’s say you have a number like 12.
You want to break it into smaller numbers that are only divisible by 1 and themselves — those are called prime numbers.

So, prime factorization just means:
Breaking a number into prime numbers that multiply together to give the original number.

Step-by-Step Example: Prime Factorization of 12

We start with 12.

Step 1: Start dividing by the smallest prime number, which is 2.

  • 12 ÷ 2 = 6
    So we write down 2

Step 2: Divide 6 by 2 again:

  • 6 ÷ 2 = 3
    So we write down another 2

Step 3: Now divide 3 by the next smallest prime.

3 is already a prime number!

  • 3 ÷ 3 = 1
    So we write down 3

Now we stop because we reached 1.

So, we have:
12 = 2 × 2 × 3

That’s the prime factorization of 12.

What Are Prime Numbers Again?

Just remember:
A prime number is a number that can’t be divided evenly by any number except 1 and itself.

  • Prime: 2, 3, 5, 7, 11…
  • Not Prime: 4 (because 2 × 2), 6 (because 2 × 3)

Now, Let’s learn how to do prime factorization in Python.

Try It Yourself: Prime Factorization Web App

Want to see how prime factorization works in real time?

Use our interactive Prime Factorization Web App below. Just enter any number, and the tool will instantly break it down into its prime factors. This is a great way to test the algorithms we discussed above and explore more examples on your own.

Whether you’re learning, teaching, or just curious, this tool helps reinforce the logic behind factorization — visually and interactively.

Prime Factorization Calculator

Prime Factorization Calculator

Find the prime factors of any positive integer

Try These Examples:

Calculating prime factors…

Results

Prime Factorization

Algorithm Information

Step-by-Step Process

Prime Factorization in Python

Prime Factorization in Python means writing a Python program that takes a number and returns the list of its prime factors — just like we do manually.

We already Know what is prime factorization. Now let’s Write a Python function that takes a number and returns its prime factors.

Prime factorization steps of 60 illustrated in Python using while loop with code snippets and visual blocks.
Visualization of Prime Factorization in Python using While Loop with step-by-step code and factor breakdown of 60.

Python Code for Prime Factorization

def prime_factors(n):
    factors = []
    # Start with the smallest prime
    i = 2
    while i * i <= n:
        while n % i == 0:
            factors.append(i)
            n = n // i
        i += 1
    # If n is still greater than 1, it's a prime number
    if n > 1:
        factors.append(n)
    return factors

# Example usage:
number = 60
print(f"Prime factors of {number} are: {prime_factors(number)}")

Output

Prime factors of 60 are: [2, 2, 3, 5]

That means:

2 × 2 × 3 × 5 = 60

How It Works

  • It starts dividing from 2
  • It keeps dividing as long as n % i == 0
  • Once it can’t divide by a number anymore, it moves to the next
  • When the square of i exceeds n, and n is still greater than 1, that last n is a prime factor

Test with Other Numbers

Try changing the number in this line:

number = 60

To 84, 97, or any number you want.

Now we know the basics of prime factorization and also we know how to implement prime factorization in python. It’s time to know why prime factorization is important in python.

Why Prime Factorization is Important in Python

Prime factorization is important in Python (and in programming in general) because it plays a key role in solving a wide range of mathematical and computational problems efficiently.

1. Foundations of Number Theory

Prime factorization is at the heart of number theory — which is used in many core algorithms in Python. If you’re doing anything with divisibility, GCD/LCM, or simplifying fractions, we need prime factorization.

Example:

To calculate LCM of two numbers, we use:

LCM(a, b) = (a × b) / GCD(a, b)

You can find the GCD efficiently using prime factors.

2. Cryptography and Security

Prime factorization is the backbone of encryption algorithms like RSA, which protect data online. These algorithms rely on the fact that factorizing large numbers is hard for computers.

So, if you ever work on data security, blockchain, or password encryption, understanding prime factorization in Python is critical.

3. Problem Solving & Coding Challenges

Many coding challenges (like those on LeetCode, HackerRank, or in Python competitions) require breaking a number into its prime factors.

Example challenges:

  • Find how many numbers have the same set of prime factors
  • Count unique primes in a range
  • Determine if a number is square-free

4. Optimizing Algorithms

In competitive programming, understanding how numbers behave through their prime factors can help you optimize solutions and avoid brute force approaches.

Example:

Rather than looping through all numbers to check if they divide another, you can work only with prime divisors. This saves time.

5. Mathematical Applications in AI, ML, and Data Science

Even in data science, you may encounter models or optimizations that require factor-based decompositions (especially in discrete mathematics, modular arithmetic, or signal processing). Being able to handle prime factorization programmatically in Python becomes useful.

Now, it’s time to explore different methods to find prime factorization in Python. We’ve already seen the basic method using a while loop, so let’s jump straight into the next ones.

Now Let’s learn how to do Prime Factorization in Python using a Helper Function.

Prime Factorization in Python using a Helper Function

Before we write a Python program that uses a helper function, we should clearly understand what a helper function is and why we use it.

Step-by-step diagram of the prime factorization algorithm using a helper function in Python, including logical flow and return steps.
Algorithm Steps for Prime Factorization in Python Using a Helper Function — from input to return.

What is a Helper Function?

A helper function is a small function that helps a larger/main function do its job.

Instead of writing one big messy function, we break the problem into smaller parts. Each part can be written as a helper function to keep the code clean and easy to understand.

for example we can create:

  • A main function: prime_factors()
  • A helper function: is_prime() to check if a number is prime.

Example: Prime Factorization with a Helper Function

# Helper function to check if a number is prime
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

# Main function for prime factorization
def prime_factors(n):
    factors = []
    for i in range(2, n+1):
        if is_prime(i):
            while n % i == 0:
                factors.append(i)
                n = n // i
        if n == 1:
            break
    return factors

# Example usage
num = 84
print(f"Prime factors of {num} are: {prime_factors(num)}")

Output:

Prime factors of 84 are: [2, 2, 3, 7]

How It Works:

  1. The is_prime() helper function checks if a number is prime.
  2. The prime_factors() function:
    • Loops through all numbers from 2 to n
    • Uses is_prime() to check if the number is prime
    • If it is, and it divides n, we keep dividing and store the factor

Why Use a Helper Function?

  • It makes the code cleaner and easier to understand
  • You can reuse helper functions in other programs
  • It’s easier to debug and test smaller pieces

Bonus Tip: More Efficient Version

Instead of checking for all primes up to n, we can optimize the loop to go up to sqrt(n):

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

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

Now, let’s move on to the next method Using a Prime Sieve for Fast Factorization (for multiple queries).

Using a Prime Sieve for Fast Factorization (for multiple queries)

Using a Prime Sieve (like the Sieve of Eratosthenes) is a smart way to speed up prime factorization, especially when you’re handling multiple queries (i.e., factoring many numbers quickly).

Problem with Basic Methods

If you use the basic prime factorization logic (like trial division), it works fine for one number. But if you need to factor hundreds or thousands of numbers, it gets slow.

So, what can we do?

Solution: Precompute with a Prime Sieve

We precompute the smallest prime factor (SPF) for every number up to a limit (say 100,000). Then, we can factor any number in O(log n) time using this data.

Step-by-Step Approach

Step 1: Build the SPF (Smallest Prime Factor) array using a sieve.

Step 2: For each number, use the SPF array to get its prime factors fast.

Python Code for Fast Prime Factorization Using a Sieve

# Step 1: Build the smallest prime factor (SPF) array
def build_spf(limit):
    spf = [0] * (limit + 1)
    for i in range(2, limit + 1):
        spf[i] = i  # Initially assume every number is prime

    for i in range(2, int(limit**0.5) + 1):
        if spf[i] == i:  # If i is still marked as prime
            for j in range(i*i, limit + 1, i):
                if spf[j] == j:
                    spf[j] = i  # Mark the smallest prime factor
    return spf

# Step 2: Use SPF array to factor numbers quickly
def get_prime_factors(n, spf):
    factors = []
    while n != 1:
        factors.append(spf[n])
        n = n // spf[n]
    return factors

# Example usage:
LIMIT = 100000
spf = build_spf(LIMIT)

queries = [60, 84, 97, 210]  # multiple numbers to factor
for num in queries:
    print(f"Prime factors of {num}: {get_prime_factors(num, spf)}")

Output:

Prime factors of 60: [2, 2, 3, 5]
Prime factors of 84: [2, 2, 3, 7]
Prime factors of 97: [97]
Prime factors of 210: [2, 3, 5, 7]

Goal of the Code:

We want to factor many numbers quickly, so we:

  1. Precompute the smallest prime factor (SPF) for every number up to a limit.
  2. Use that SPF table to factor any number in logarithmic time.

Part 1: Building the SPF Array

def build_spf(limit):
    spf = [0] * (limit + 1)  # Create a list to store smallest prime factors for every number
    for i in range(2, limit + 1):
        spf[i] = i  # Initially assume each number is prime (so its SPF is itself)
What’s Happening?

We create a list called spf (Smallest Prime Factor).
For example, if limit = 10, we get:

spf = [0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We’ll fix the wrong entries later by finding the smallest prime that divides each number.

Now Apply the Sieve
    for i in range(2, int(limit**0.5) + 1):
        if spf[i] == i:  # Means 'i' is a prime number
            for j in range(i * i, limit + 1, i):
                if spf[j] == j:  # If 'j' is still marked as prime
                    spf[j] = i  # Then 'i' is the smallest prime factor of 'j'
What’s Going On Here?

We use the classic Sieve of Eratosthenes idea:

  • Start from 2, the first prime.
  • For each multiple of i (like 2i, 3i, etc.), we mark it with its smallest prime factor.
  • We only update spf[j] if it hasn’t been changed yet (i.e., still marked as a prime).

So for example:

  • spf[4] becomes 2
  • spf[6] becomes 2
  • spf[9] becomes 3
  • etc.

Final Step:

    return spf

Now we have a ready-to-use SPF table

Part 2: Fast Prime Factorization Using the SPF Table

def get_prime_factors(n, spf):
    factors = []
    while n != 1:
        factors.append(spf[n])  # Add the smallest prime factor of 'n'
        n = n // spf[n]         # Divide 'n' by that prime factor and continue
    return factors

What’s Happening?

Let’s say you want to factor 60, and spf[60] = 2.
You do:

  1. Add 2 to the list
  2. Do 60 // 2 = 30
  3. Then spf[30] = 2, so add another 2
  4. 30 // 2 = 15, now spf[15] = 3
  5. 15 // 3 = 5, spf[5] = 5
  6. Now n = 1, so stop

Output becomes:

[2, 2, 3, 5]

Putting It All Together

LIMIT = 100000
spf = build_spf(LIMIT)  # Precompute once

queries = [60, 84, 97, 210]  # These are the numbers we want to factor
for num in queries:
    print(f"Prime factors of {num}: {get_prime_factors(num, spf)}")

Example Output:

Prime factors of 60: [2, 2, 3, 5]
Prime factors of 84: [2, 2, 3, 7]
Prime factors of 97: [97]
Prime factors of 210: [2, 3, 5, 7]

Each query runs very fast, because the hard work was done earlier using the sieve.

Summary

ConceptPurpose
spf[]Stores the smallest prime factor for every number
build_spf(limit)Fills the spf array efficiently using the sieve
get_prime_factors(n, spf)Uses spf to factor any number in O(log n) time
Main BenefitIdeal for multiple queries and large numbers

This is a great approach when working with a range of numbers in applications like data science or competitive coding.

Prime Factorization Quiz & FAQ

Prime Factorization Quiz

Test your understanding of prime factorization algorithms and Python implementation

Question 1 of 8

Frequently Asked Questions

Common questions about prime factorization algorithms

What is prime factorization?

+

Prime factorization is the process of breaking down a composite number into its prime factors. For example, the prime factorization of 12 is 2² × 3, meaning 12 = 2 × 2 × 3. Every positive integer greater than 1 either is prime itself or can be represented as a unique product of prime numbers.

What is the time complexity of the basic prime factorization algorithm?

+

The basic trial division algorithm has a time complexity of O(√n), where n is the number being factorized. This is because we only need to check divisors up to the square root of n. More advanced algorithms like Pollard’s rho algorithm can achieve better performance for large numbers.

How do you optimize prime factorization in Python?

+

Several optimizations can be applied: 1) Check for 2 separately and then only check odd numbers, 2) Use a sieve to generate primes up to √n, 3) Implement wheel factorization, 4) Use libraries like sympy for large numbers, 5) Apply parallel processing for multiple factorizations.

When should you use prime factorization?

+

Prime factorization is useful in: 1) Cryptography (RSA encryption), 2) Finding GCD and LCM, 3) Simplifying fractions, 4) Number theory problems, 5) Competitive programming, 6) Mathematical proofs, 7) Analyzing periodic functions and sequences.

What are the limitations of prime factorization?

+

The main limitations include: 1) Exponential time complexity for large numbers with large prime factors, 2) Memory constraints for storing intermediate results, 3) Difficulty in factorizing numbers that are products of two large primes (basis of RSA security), 4) Not efficient for real-time applications with large inputs.

How does Python’s math module help with prime factorization?

+

Python’s math module provides several useful functions: 1) math.gcd() for finding greatest common divisor, 2) math.isqrt() for integer square root, 3) math.sqrt() for floating-point square root, 4) math.ceil() and math.floor() for rounding. For advanced factorization, consider using sympy.factorint() which implements sophisticated algorithms.

What’s the difference between trial division and advanced factorization methods?

+

Trial division is the simplest method, testing divisibility by all numbers up to √n. Advanced methods include: 1) Pollard’s rho algorithm (faster for composite numbers), 2) Quadratic sieve (for large numbers), 3) Elliptic curve factorization, 4) General number field sieve (most efficient for very large numbers). These methods use mathematical properties to reduce the search space significantly.

How do you handle edge cases in prime factorization?

+

Important edge cases to handle: 1) n ≤ 1 (return empty or error), 2) n = 2 (smallest prime), 3) Even numbers (factor out 2 first), 4) Perfect squares (check if √n is prime), 5) Prime numbers (return [n]), 6) Large numbers (use appropriate algorithms), 7) Zero and negative numbers (define behavior clearly).

Conclusion

Prime factorization is a powerful concept that connects mathematics with real-world coding problems. Whether you’re solving coding challenges or building cryptographic tools, this is a must-know skill.

With just a few lines of Python code, you can factor any number and unlock its mathematical building blocks.

External Resources for Further Reading

1. Python’s Official Documentation – math Module

Learn about built-in functions that can assist in number operations.
https://docs.python.org/3/library/math.html

2. Khan Academy – Prime Factorization Basics

Great for understanding the mathematical foundation behind prime factorization.
https://www.khanacademy.org/math/arithmetic/factors-multiples/prime-factorization/v/prime-factorization

3. Wikipedia – Prime Factorization

For historical context and theoretical background.
https://en.wikipedia.org/wiki/Integer_factorization

Test Yourself: Prime Factorization Coding Challenges

Prime Factorization Coding Challenges

Prime Factorization Coding Challenges

Master prime factorization algorithms for coding interviews

Your Progress

0 of 9 challenges completed

0
Easy Solved
0
Medium Solved
0
Hard Solved

About The Author

Leave a Reply

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

  • Rating