Given a range [L, R]. The task is to find the sum of all the prime numbers in the given range from L to R both inclusive.
Input : L = 10, R = 20 Output : Sum = 60 Prime numbers between [10, 20] are: 11, 13, 17, 19 Therefore, sum = 11 + 13 + 17 + 19 = 60 Input : L = 15, R = 25 Output : Sum = 59
A Simple Solution is to traverse from L to R, check if the current number is prime. If yes, add it to . Finally, print the sum.
An Efficient Solution is to use Sieve of Eratosthenes to find all primes up to a given limit. Then, compute a prefix sum array to store sum till every value before the limit. Once we have prefix array, We just need to return prefix[R] – prefix[L-1].
Note: prefix[i] will store the sum of all prime numbers from 1 to .
Below is the implementation of the above approach:
# Python 3 program to find sum of primes
# in range L to R
from math import sqrt
MAX = 10000
# prefix[i] is going to store sum of primes
# till i (including i).
prefix = [0 for i in range(MAX + 1)]
# Function to build the prefix sum array
# Create a boolean array “prime[0..n]”. A
# value in prime[i] will finally be false
# if i is Not a prime, else true.
prime = [True for i in range(MAX + 1)]
for p in range(2,int(sqrt(MAX)) + 1, 1):
# If prime[p] is not changed, then
# it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, MAX + 1, p):
prime[i] = False
# Build prefix array
prefix = 0
prefix = 0
for p in range(2, MAX + 1, 1):
prefix[p] = prefix[p – 1]
prefix[p] += p
# Function to return sum of prime in range
def sumPrimeRange(L, R):
return prefix[R] – prefix[L – 1]
# Driver code
if __name__ == ‘__main__’:
L = 10
R = 20
# This code is contributed by
- Segmented Sieve (Print Primes in a Range)
- Sieve of Eratosthenes
- Sieve of Eratosthenes in 0(n) time complexity
- Sieve of Sundaram to print all primes smaller than n
- Product of all primes in the range from L to R
- K-Primes (Numbers with k prime factors) in a range
- Length of largest sub-array having primes strictly greater than non-primes
- Count primes that can be expressed as sum of two consecutive primes and 1
- Segmented Sieve
- Bitwise Sieve
- Sieve of Atkin
- Prime Factorization using Sieve O(log n) for multiple queries
- Number of unmarked integers in a special sieve
- Circular primes less than n
- Palindromic Primes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.