Try These Examples:
Calculating prime factors…
Prime Factorization Algorithm in Python – Ultra High-Quality Visual A stunning visual representation of a prime factorization algorithm in Python, featuring beautifully styled code, factor breakdown of 180, and key performance details.
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.
We start with 12.
3 is already a prime number!
Now we stop because we reached 1.
So, we have:
12 = 2 × 2 × 3
That’s the prime factorization of 12.
Just remember:
A prime number is a number that can’t be divided evenly by any number except 1 and itself.
Now, Let’s learn how to do prime factorization in Python.
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.
Find the prime factors of any positive integer
Calculating prime factors…
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.
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
n % i == 0i exceeds n, and n is still greater than 1, that last n is a prime factorTry 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.
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.
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.
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.
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.
Many coding challenges (like those on LeetCode, HackerRank, or in Python competitions) require breaking a number into its prime factors.
Example challenges:
In competitive programming, understanding how numbers behave through their prime factors can help you optimize solutions and avoid brute force approaches.
Rather than looping through all numbers to check if they divide another, you can work only with prime divisors. This saves time.
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
whileloop, so let’s jump straight into the next ones.
Now Let’s learn how to do 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.
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:
prime_factors()is_prime() to check if a number is prime.# 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]
is_prime() helper function checks if a number is prime.prime_factors() function: nis_prime() to check if the number is primen, we keep dividing and store the factorInstead 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 (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).
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?
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 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.
# 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]
We want to factor many numbers quickly, so we:
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)
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.
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'
We use the classic Sieve of Eratosthenes idea:
i (like 2i, 3i, etc.), we mark it with its smallest prime factor.spf[j] if it hasn’t been changed yet (i.e., still marked as a prime).So for example:
spf[4] becomes 2spf[6] becomes 2spf[9] becomes 3Final Step:
return spf
Now we have a ready-to-use 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
Let’s say you want to factor 60, and spf[60] = 2.
You do:
2 to the list60 // 2 = 30spf[30] = 2, so add another 230 // 2 = 15, now spf[15] = 315 // 3 = 5, spf[5] = 5n = 1, so stopOutput 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.
| Concept | Purpose |
|---|---|
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 Benefit | Ideal 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 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.
math ModuleLearn about built-in functions that can assist in number operations.
https://docs.python.org/3/library/math.html
Great for understanding the mathematical foundation behind prime factorization.
https://www.khanacademy.org/math/arithmetic/factors-multiples/prime-factorization/v/prime-factorization
For historical context and theoretical background.
https://en.wikipedia.org/wiki/Integer_factorization
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.