Sum of all the Prime Numbers in a given Range in Python

I was working on a Python project where I needed to calculate the sum of all prime numbers within a specific range. At first, it sounded simple, but I quickly realized that many beginners find it tricky to identify prime numbers correctly and then sum them up efficiently.

I’ve faced this requirement multiple times. Whether it was for a small data encryption task, a mathematical analysis, or even a coding interview preparation, summing prime numbers comes up often.

In this tutorial, I’ll walk you through different methods I use to calculate the sum of prime numbers in a given range.

Prime Number

Before we start coding, let’s quickly recap what a prime number is.

A prime number is a number greater than 1 that has no divisors other than 1 and itself. For example:

  • 2, 3, 5, 7, 11, 13 are prime numbers.
  • 4, 6, 8, 9, 10 are not prime numbers because they can be divided by other numbers.

So, when we talk about summing prime numbers in a range, we’re essentially filtering out all primes within that range and then adding them together.

Method 1 – Use a Simple Loop and Prime Check Function in Python

The easy way is to write a helper function that checks if a number is prime, and then loop through the given range to sum all primes in Python.

Here is the full code:

def is_prime(num):
    """Check if a number is prime."""
    if num <= 1:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

def sum_of_primes(start, end):
    """Return the sum of prime numbers in a given range."""
    total = 0
    for num in range(start, end + 1):
        if is_prime(num):
            total += num
    return total

# Example usage
start_range = 10
end_range = 50
print("Sum of prime numbers between", start_range, "and", end_range, "is:", sum_of_primes(start_range, end_range))

You can see the output in the screenshot below.

sum of prime numbers in python

Explanation

  • The is_prime() function checks if a number is prime.
  • The sum_of_primes() function loops through the given range (start to end), checks each number, and adds it to the total if it’s prime.
  • In the example, the sum of prime numbers between 10 and 50 is calculated.

This method is simple and works well for small to medium ranges.

Method 2 – Use Python List Comprehension

Python allows us to write more compact code using list comprehensions. Instead of writing multiple loops, we can calculate the sum in a single line.

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

def sum_of_primes(start, end):
    return sum([num for num in range(start, end + 1) if is_prime(num)])

# Example usage
print(sum_of_primes(1, 100))

You can see the output in the screenshot below.

python sum range

This method is cleaner and more Pythonic. It’s also easy to read once you get comfortable with list comprehensions.

Method 3 – Use the Sieve of Eratosthenes

If you are working with large ranges (say up to 1 million), the previous methods might become slow. In such cases, I prefer using the Sieve of Eratosthenes, which is one of the most efficient algorithms for finding prime numbers.

def sieve_sum_of_primes(start, end):
    """Calculate sum of primes using Sieve of Eratosthenes."""
    sieve = [True] * (end + 1)
    sieve[0:2] = [False, False]  # 0 and 1 are not prime

    for i in range(2, int(end ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, end + 1, i):
                sieve[j] = False

    return sum(i for i in range(start, end + 1) if sieve[i])

# Example usage
print(sieve_sum_of_primes(1, 1000))

You can see the output in the screenshot below.

python for loop sum range example
  • It’s much faster for large ranges.
  • Instead of checking each number individually, it marks multiples of primes as non-prime in one pass.
  • Once the sieve is built, summing primes is simple.

Practical Example

Let’s say I want to calculate the sum of prime numbers between 1 and 100,000. Using the sieve method, Python can compute it within seconds.

print("Sum of primes between 1 and 100000 is:", sieve_sum_of_primes(1, 100000))

This type of calculation is useful in cryptography, data analysis, and even in algorithmic coding interviews.

Common Mistakes to Avoid

  1. Forgetting that 1 is not a prime number.
    Many beginners mistakenly include 1 as prime, which gives incorrect results.
  2. Not optimizing the prime check.
    Always check divisibility up to the square root of the number instead of checking all numbers.
  3. Using brute force for very large ranges.
    If you need primes up to millions, always use the Sieve of Eratosthenes.

When Should You Use Each Method?

  • Method 1 (Simple Loop): Best for beginners and small ranges (like 1–1000).
  • Method 2 (List Comprehension): Great for writing clean, compact code.
  • Method 3 (Sieve of Eratosthenes): Ideal for large datasets where performance matters.

Summing prime numbers in a given range is a common Python task, and there are multiple ways to approach it. I start with the simple loop method when I’m teaching beginners, and then I move to the sieve method when performance becomes important.

If you’re preparing for coding interviews or working on real-world projects like cryptography or data analysis, mastering these methods will save you a lot of time.

You may like to 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.