Related Articles
Sum of all the prime numbers in a given range
• Difficulty Level : Hard
• Last Updated : 17 Dec, 2020

Given a range [l, r], the task is to find the sum of all the prime numbers within that range.
Examples:

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:

## C++

 // C++ Program to computer sum of prime number// in a given range#include using namespace std; // Method to compute the prime number// Time Complexity is O(sqrt(N))bool checkPrime(int numberToCheck){    if(numberToCheck == 1) {        return false;    }    for (int i = 2; i*i <= numberToCheck; i++) {        if (numberToCheck % i == 0) {            return false;        }    }    return true;} // Method to iterate the loop from l to r// If the current number is prime, sum the valueint primeSum(int l, int r){    int sum = 0;    for (int i = r; i >= l; i--) {         // Check for prime        bool isPrime = checkPrime(i);        if (isPrime) {             // Sum the prime number            sum = sum + i;        }    }    return sum;}// Time Complexity is O(r x sqrt(N)) //Driver codeint main(){    int l = 4, r = 13;     // Call the method with l and r    cout << primeSum(l, r);}

## Java

 // Java Program to computer sum of prime number// in a given rangepublic class GFG {     // Method to compute the prime number    // Time Complexity is O(sqrt(N))    static boolean checkPrime(int numberToCheck)    {        if(numberToCheck == 1) {            return false;        }        for (int i = 2; i*i <= numberToCheck; i++) {            if (numberToCheck % i == 0) {                return false;            }        }        return true;    }     // Method to iterate the loop from l to r    // If prime number detects, sum the value    static int primeSum(int l, int r)    {        int sum = 0;        for (int i = r; i >= l; i--) {             // Check for prime            boolean isPrime = checkPrime(i);            if (isPrime) {                 // Sum the prime number                sum = sum + i;            }        }        return sum;    }    // Time Complexity is O(r x sqrt(N))     // Driver code    public static void main(String[] args)    {        int l = 4, r = 13;         // Call the method with l and r        System.out.println(primeSum(l, r));    }}

## Python 3

 # Python3 Program to computer sum# of prime number in a given range # from math lib import sqrt methodfrom math import sqrt # Function to compute the prime number# Time Complexity is O(sqrt(N))def checkPrime(numberToCheck) :     if numberToCheck == 1 :        return False     for i in range(2, int(sqrt(numberToCheck)) + 1) :         if numberToCheck % i == 0 :            return False     return True # Function to iterate the loop# from l to r. If the current# number is prime, sum the valuedef primeSum(l, r) :     sum = 0     for i in range(r, (l - 1), -1) :         # Check for prime        isPrime = checkPrime(i)                 if (isPrime) :             # Sum the prime number            sum += i     return sum # Time Complexity is O(r x sqrt(N)) # Driver code    if __name__ == "__main__" :     l, r = 4, 13     # Call the function with l and r    print(primeSum(l, r)) # This code is contributed# by ANKITRAI1

## C#

 // C# Program to computer sum// of prime number in a given rangeusing System; class GFG{ // Method to compute the prime// number Time Complexity is O(sqrt(N))static bool checkPrime(int numberToCheck){    if(numberToCheck == 1)    {        return false;    }    for (int i = 2;             i * i <= numberToCheck; i++)    {        if (numberToCheck % i == 0)        {            return false;        }    }    return true;} // Method to iterate the loop from l to r// If prime number detects, sum the valuestatic int primeSum(int l, int r){    int sum = 0;    for (int i = r; i >= l; i--)    {         // Check for prime        bool isPrime = checkPrime(i);        if (isPrime)        {             // Sum the prime number            sum = sum + i;        }    }    return sum;}// Time Complexity is O(r x sqrt(N)) // Driver codepublic static void Main(){    int l = 4, r = 13;     // Call the method with l and r    Console.Write(primeSum(l, r));}} // This code is contributed// by ChitraNayal

## PHP

 = $l; $i--)    {         // Check for prime        $isPrime = checkPrime($i);        if ($isPrime) {  // Sum the prime number $sum = $sum + $i;        }    }    return $sum;} // Time Complexity is O(r x sqrt(N)) // Driver code$l = 4; $r = 13; // Call the method with l and recho primeSum($l, \$r); // This code is contributed by ajit?>

Output:

36

Time Complexity: Space Complexity: Approach 2: (Dynamic Programming)

1. Declare an array dp and arr
2. Fill the array arr to 0
3. 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
4. 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]

Image Representation ## C++

 // C++ Program to computer sum of prime number// in a given range#include using namespace std; // Suppose the constraint is N<=1000const int N = 1000; // Declare an array for dynamic approachint dp[N + 1]; // Method to compute the arrayvoid sieve(){    // Declare an extra array as arr    int arr[N + 1];    arr = 1;    arr = 1;     // Iterate the loop till sqrt(n)    // Time Complexity is O(log(n) X sqrt(n))    for (int i = 2; i <= sqrt(N); i++)         // if ith element of arr is 0 i.e. marked as prime        if (arr[i] == 0)             // mark all of it's multiples till N as non-prime            // by setting the locations to 1            for (int j = i * i; j <= N; j += i)                arr[j] = 1;     long runningPrimeSum = 0;     // Update the array 'dp' with the running sum    // of prime numbers within the range [1, N]    // Time Complexity is O(n)    for (int i = 1; i <= N; i++)    {        if (arr[i] == 0)            runningPrimeSum += i;         // Here, dp[i] is the sum of all the prime numbers        // within the range [1, i]        dp[i] = runningPrimeSum;    }} // Driver codeint main(){    int l = 4, r = 13;       // Compute dp    sieve();    cout << dp[r] - dp[l - 1];     return 0;} // This code is contributedd by divyesh072019

## Java

 // Java Program to computer sum of prime number// in a given rangepublic class GFG {     // Suppose the constraint is N<=1000    static int N = 1000;     // Declare an array for dynamic approach    static long dp[] = new long[N + 1];     // Method to compute the array    static void sieve()    {        // Declare an extra array as arr        int arr[] = new int[N + 1];        arr = 1;        arr = 1;         // Iterate the loop till sqrt(n)        // Time Complexity is O(log(n) X sqrt(n))        for (int i = 2; i <= Math.sqrt(N); i++)             // if ith element of arr is 0 i.e. marked as prime            if (arr[i] == 0)                 // mark all of it's multiples till N as non-prime                // by setting the locations to 1                for (int j = i * i; j <= N; j += i)                    arr[j] = 1;         long runningPrimeSum = 0;         // Update the array 'dp' with the running sum        // of prime numbers within the range [1, N]        // Time Complexity is O(n)        for (int i = 1; i <= N; i++) {            if (arr[i] == 0)                runningPrimeSum += i;             //Here, dp[i] is the sum of all the prime numbers            //within the range [1, i]            dp[i] = runningPrimeSum;        }    }     // Driver code    public static void main(String[] args)    {        int l = 4, r = 13;         // Compute dp        sieve();        System.out.println(dp[r] - dp[l - 1]);    }}

## Python 3

 # Python3 Program to computer sum of prime number# in a given rangeimport math # for sqrt and ceil function # Suppose the constraint is N<=1000N = 1000 # Declare an array for dynamic approachdp =  * (N + 1) # Method to compute the arraydef seive():     # Declare an extra array as array    array =  * (N + 1)         array = 1    array = 1     # Iterate the loop till sqrt(N)    # Time Complexity is O(log(n) X sqrt(N))    for i in range(2, math.ceil(math.sqrt(N) + 1)):         # if ith element of arr is 0        # i.e. marked as prime        if array[i] == 0:                         # mark all of it's multiples till N as            # non-prime by setting the locations to 1            for j in range(i * i, N + 1, i):                array[j] = 1         runningPrimeSum = 0     # Update the array 'dp' with the running sum    # of prime numbers within the range [1, N]    # Time Complexity is O(n)    for i in range(1, N + 1):        if array[i] == 0:            runningPrimeSum += i             # Here, dp[i] is the sum of all the prime numbers        # within the range [1, i]        dp[i] = runningPrimeSum # Driver Codel = 4r = 13seive()print(dp[r] - dp[l - 1]) # This code is contributed by Vivek Kumar Singh

## C#

 // C# Program to computer sum of prime number// in a given rangeusing System;public class GFG {      // Suppose the constraint is N<=1000    static int N = 1000;     // Declare an array for dynamic approach    static long[] dp = new long[N + 1];     // Method to compute the array    static void sieve()    {        // Declare an extra array as arr        int []arr = new int[N + 1];        arr = 1;        arr = 1;         // Iterate the loop till sqrt(n)        // Time Complexity is O(log(n) X sqrt(n))        for (int i = 2; i <= Math.Sqrt(N); i++)             // if ith element of arr is 0 i.e. marked as prime            if (arr[i] == 0)                 // mark all of it's multiples till N as non-prime                // by setting the locations to 1                for (int j = i * i; j <= N; j += i)                    arr[j] = 1;         long runningPrimeSum = 0;         // Update the array 'dp' with the running sum        // of prime numbers within the range [1, N]        // Time Complexity is O(n)        for (int i = 1; i <= N; i++) {            if (arr[i] == 0)                runningPrimeSum += i;             //Here, dp[i] is the sum of all the prime numbers            //within the range [1, i]            dp[i] = runningPrimeSum;        }    }     // Driver code    public static void Main()    {        int l = 4, r = 13;         // Compute dp        sieve();        Console.WriteLine(dp[r] - dp[l - 1]);    }}  /*This code is contributed by 29AjayKumar*/

Output:

36

Time Complexity: Space Complexity: 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.

My Personal Notes arrow_drop_up