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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Segmented Sieve (Print Primes in a Range)
- 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))?
- Sieve of Sundaram to print all primes smaller than n
- Product of all primes in the range from L to R
- Minimum difference between any two primes from the given range
- K-Primes (Numbers with k prime factors) in a range
- Length of largest sub-array having primes strictly greater than non-primes
- Minimum window size containing atleast P primes in every window of 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
- Bitwise Sieve
- 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 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.