How to Get the Next Prime Number in Python

Finding prime numbers is a task I find myself doing quite often, especially when working on data encryption or complex mathematical simulations.

While it sounds like a simple math problem, doing it efficiently in Python requires a bit of thought, especially as the numbers get larger.

In my years of developing backend systems, I’ve had to generate prime IDs for unique indexing in database clusters across different US data centers.

In this tutorial, I will show you exactly how to find the next largest prime number after any given integer using a few different methods.

What is a Prime Number?

Before we jump into the code, let’s quickly refresh our memory on what a prime number actually is.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

For example, if you are looking at the population of a small town in Wyoming, say 1,013 people, that number is prime because nothing divides into it evenly except 1 and 1,013.

Method 1: Use a Simple While Loop and a Helper Function

The easy way to find the next prime number is to create a helper function that checks if a number is prime.

Then, I use a while loop that starts from our given number and increments by one until the helper function returns True.

Here is how I usually write this out:

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

# Function to find the next largest prime
def get_next_prime(number):
    next_num = number + 1
    while True:
        if is_prime(next_num):
            return next_num
        next_num += 1

# Example: Finding the next prime after a US ZIP code
zip_code = 90210
next_prime_zip = get_next_prime(zip_code)

print(f"The next prime number after the Beverly Hills ZIP code {zip_code} is {next_prime_zip}")

I executed the above example code and added the screenshot below.

find next prime number

In the code above, the is_prime function only checks up to the square root of the number. I found that this optimization is crucial because it significantly reduces the number of iterations needed.

If you were to check every number up to n, your script would crawl to a halt once you start dealing with large financial figures, like the US National Debt increments.

Method 2: Optimize with Step Increments

One thing I noticed early in my career is that all prime numbers greater than 2 are odd.

We can use this knowledge to make our search twice as fast by skipping all even numbers in our loop.

This is a great approach if you are building an application for a logistics company in Chicago that needs to calculate prime-based route IDs.

def is_prime_optimized(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def find_next_prime_fast(number):
    if number < 2:
        return 2
    
    # Start searching from the next number
    next_num = number + 1
    
    # If the next number is even, make it odd
    if next_num % 2 == 0:
        next_num += 1
        
    while True:
        if is_prime_optimized(next_num):
            return next_num
        next_num += 2  # Skip even numbers

# Example: Calculating a prime ID for a shipment from New York to LA
shipment_weight = 5504
next_prime_id = find_next_prime_fast(shipment_weight)

print(f"The assigned Prime ID for the shipment {shipment_weight} lbs is {next_prime_id}")

I executed the above example code and added the screenshot below.

how to find the next prime number

I prefer this method when I am working in an environment where I cannot install third-party libraries.

The i + 6 logic is based on the fact that all primes greater than 3 can be expressed in the form $6k \pm 1$.

It saves a massive amount of CPU cycles, especially when processed on a cloud server instance where you pay for compute time.

Method 3: Use the SymPy Library (The Professional Way)

If you are working on a professional data science project or a FinTech app in Manhattan, you likely already have access to the SymPy library.

SymPy is a Python library for symbolic mathematics, and it has a built-in function called nextprime().

First, you’ll need to install it:

pip install sympy

Then, you can use it like this:

from sympy import nextprime

# Example: Finding the next prime for a high-frequency trading signal
trading_signal_value = 12450
next_prime_signal = nextprime(trading_signal_value)

print(f"The next prime after the trading signal {trading_signal_value} is {next_prime_signal}")

# You can even go backwards if needed
from sympy import prevprime
print(f"The prime before the signal is {prevprime(trading_signal_value)}")

I executed the above example code and added the screenshot below.

how to find next prime number

In my experience, using a battle-tested library is always better than reinventing the wheel.

The nextprime function in SymPy uses extremely sophisticated primality tests (like the Miller-Rabin test).

It can handle numbers with hundreds of digits in a fraction of a second, which is perfect for modern encryption needs.

Which Method Should You Choose?

I usually base my decision on the specific requirements of the project I am working on.

If I am writing a small script to organize files on my local machine in Seattle, Method 1 is perfectly fine.

However, if I am building a production-grade API that will be hit by thousands of users across the United States, I always go with Method 3.

If you are in a situation where you are restricted from using external packages (like in some highly secure corporate environments), Method 2 is your best friend.

Handle Very Large Numbers

When dealing with massive numbers—like the number of stars in the galaxy or the total number of transactions processed by a major US bank—Python handles the size automatically.

Unlike other languages, Python’s integers have arbitrary precision.

This means your only real bottleneck will be the time it takes to prove a number is prime, not the size of the number itself.

Practical Use Case: Prime Number Generation for Security

In the world of cybersecurity, prime numbers are the backbone of RSA encryption.

Often, you need to find a prime number that is “close” to a specific value to generate keys.

By using the nextprime logic, you can ensure that your system generates unique, unpredictable keys for your users.

In this tutorial, I showed you three different ways to find the next largest prime number in Python.

Whether you prefer the manual logic of a while loop or the power of a library like SymPy, you now have the tools to handle prime numbers in your own projects.

I’ve used these exact methods to solve problems ranging from simple coding challenges to complex data engineering tasks.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.