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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sieve of Eratosthenes
- Sieve of Eratosthenes in 0(n) time complexity
- How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
- Segmented Sieve (Print Primes in a Range)
- Sieve of Sundaram to print all primes smaller than n
- Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
- Count primes that can be expressed as sum of two consecutive primes and 1
- Count of primes below N which can be expressed as the sum of two primes
- Length of largest sub-array having primes strictly greater than non-primes
- Count of primes in a given range that can be expressed as sum of perfect squares
- Product of all primes in the range from L to R
- Minimum difference between any two primes from the given range
- Minimum window size containing atleast P primes in every window of given range
- Prime Factorization using Sieve O(log n) for multiple queries
- Longest sub-array of Prime Numbers using Segmented Sieve
- K-Primes (Numbers with k prime factors) in a range
- Find the sum of all Truncatable primes below N
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Segmented Sieve
- Sieve of Atkin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.