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:
- 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
- Bitwise Sieve
- Segmented Sieve
- Sieve of Atkin
- Prime Factorization using Sieve O(log n) for multiple queries
- Number of unmarked integers in a special sieve
- Palindromic Primes
- Circular primes less than n
- Count Primes in Ranges
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.