Given a range [l, r], the task is to find the sum of all the prime numbers within that range.
Input : l=1 and r=6 Output : 10
Input : l=4 and r=13 Output : 36
Approach 1: (Naive Approach)
Iterate the loop from ‘l’ to ‘r’ and add all the numbers which are prime.
Below is the implementation of the above approach:
Approach 2: (Dynamic Programming)
- Declare an array dp and arr
- Fill the array arr to 0
- Iterate the loop till sqrt(N) and if
arr[i] = 0(marked as prime), then set all of it’s multiples as non-prime by marking the respective location as 1
- Update the dp array with the running prime numbers sum, where each location ‘dp[i]’ holds the sum of all the prime numbers withing the range [1, i]
# Python3 Program to computer sum of prime number
# in a given range
import math # for sqrt and ceil function
# Suppose the constraint is N
- Prime numbers in a given range using STL | Set 2
- Print prime numbers in a given range using C++ STL
- Sum of all prime divisors of all the numbers in range L-R
- Numbers in range [L, R] such that the count of their divisors is both even and prime
- Count numbers from range whose prime factors are only 2 and 3
- K-Primes (Numbers with k prime factors) in a range
- Queries for the difference between the count of composite and prime numbers in a given range
- Count numbers in a range having GCD of powers of prime factors equal to 1
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Find the highest occurring digit in prime numbers in a range
- Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Print the nearest prime number formed by adding prime numbers to N
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.