Open In App

Sum of all the prime numbers in a given range

Improve
Improve
Like Article
Like
Save
Share
Report

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 compute sum of prime number
// in a given range
#include <iostream>
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 value
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 code
int main()
{
    int l = 4, r = 13;
 
    // Call the method with l and r
    cout << primeSum(l, r);
}

                    

Java

// Java Program to compute sum of prime number
// in a given range
public 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 compute sum
# of prime number in a given range
 
# from math lib import sqrt method
from 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 value
def 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 compute sum
// of prime number in a given range
using 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 value
static 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 code
public 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

                    

Javascript

<script>
    // Javascript Program to compute sum
    // of prime number in a given range
     
    // Method to compute the prime
    // number Time Complexity is O(sqrt(N))
    function checkPrime(numberToCheck)
    {
        if(numberToCheck == 1)
        {
            return false;
        }
        for (let 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
    function primeSum(l, r)
    {
        let sum = 0;
        for (let i = r; i >= l; i--)
        {
 
            // Check for prime
            let isPrime = checkPrime(i);
            if (isPrime)
            {
 
                // Sum the prime number
                sum = sum + i;
            }
        }
        return sum;
    }
     
    let l = 4, r = 13;
  
    // Call the method with l and r
    document.write(primeSum(l, r));
 
</script>

                    

PHP

<?php
// PHP Program to compute sum of
// prime number in a given range
 
// Method to compute the prime number
// Time Complexity is O(sqrt(N))
function checkPrime($numberToCheck)
{
    if($numberToCheck == 1)
    {
        return false;
    }
    for ($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 value
function primeSum($l, $r)
{
    $sum = 0;
    for ($i = $r; $i >= $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 r
echo primeSum($l, $r);
 
// This code is contributed by ajit
?>

                    

Output
36

Time Complexity: O(n\sqrt{n})
Auxiliary Space: O(1)

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 its 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 within the range [1, i]

Below is the implementation of the above approach:

C++

// C++ Program to compute sum of prime number
// in a given range
#include <bits/stdc++.h>
using namespace std;
 
// Suppose the constraint is N<=1000
const int N = 1000;
 
// Declare an array for dynamic approach
int dp[N + 1];
 
// Method to compute the array
void sieve()
{
    // Declare an extra array as arr
    int arr[N + 1]={0};
    arr[0] = 1;
    arr[1] = 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 code
int main()
{
    int l = 4, r = 13;
   
    // Compute dp
    sieve();
    cout << dp[r] - dp[l - 1];
 
    return 0;
}
 
// This code is contributed by divyesh072019

                    

Java

// Java Program to compute sum of prime number
// in a given range
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[0] = 1;
        arr[1] = 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 compute sum of prime number
# in a given range
import math # for sqrt and ceil function
 
# Suppose the constraint is N<=1000
N = 1000
 
# Declare an array for dynamic approach
dp = [0] * (N + 1)
 
# Method to compute the array
def sieve():
 
    # Declare an extra array as array
    array = [0] * (N + 1)
     
    array[0] = 1
    array[1] = 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 Code
l = 4
r = 13
sieve()
print(dp[r] - dp[l - 1])
 
# This code is contributed by Vivek Kumar Singh

                    

C#

// C# Program to compute sum of prime number
// in a given range
using 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[0] = 1;
        arr[1] = 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*/

                    

Javascript

<script>
// Javascript Program to compute sum of prime number
// in a given range
     
    // Suppose the constraint is N<=1000
    let N = 1000;
     
    // Declare an array for dynamic approach
    let dp=new Array(N+1);
    for(let i=0;i<dp.length;i++)
    {
        dp[i]=0;
    }
    // Method to compute the array
    function sieve()
    {
        let arr=new Array(N+1);
        for(let i=0;i<arr.length;i++)
        {
            arr[i]=0;
        }
        arr[0] = 1;
        arr[1] = 1;
          
        // Iterate the loop till sqrt(n)
        // Time Complexity is O(log(n) X sqrt(n))
        for (let i = 2; i <= Math.ceil(Math.sqrt(N)+1); 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 (let j = i * i; j <= N; j += i)
                    arr[j] = 1;
  
        let runningPrimeSum = 0;
  
        // Update the array 'dp' with the running sum
        // of prime numbers within the range [1, N]
        // Time Complexity is O(n)
        for (let 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
    let l = 4, r = 13;
    // Compute dp
    sieve();
    document.write(dp[r] - dp[l - 1]);
     
     
 
// This code is contributed by avanitrachhadiya2155
</script>

                    

Output
36

Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)

New Approach:- (Approach 3) Optimized Sieve of Eratosthenes

The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a given limit. We can modify this algorithm to solve the problem of finding the sum of prime numbers in a given range.

Below is the implementation of the above approach:

C++

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
 
int primeSum(int l, int r) {
    vector<bool> isPrime(r + 1, true);
    isPrime[0] = isPrime[1] = false;
 
    for (int i = 2; i <= sqrt(r); i++) {
        if (isPrime[i]) {
            for (int j = i * i; j <= r; j += i) {
                isPrime[j] = false;
            }
        }
    }
 
    int sum = 0;
    for (int i = l; i <= r; i++) {
        if (isPrime[i]) {
            sum += i;
        }
    }
 
    return sum;
}
 
int main() {
    int l = 4, r = 13;
    cout << primeSum(l, r) << endl;
 
    return 0;
}

                    

Java

import java.util.Arrays;
 
public class Main {
 
    // Function to calculate the sum of prime numbers in the
    // range [l, r]
    static int primeSum(int l, int r)
    {
        // Create a boolean array to mark prime numbers,
        // initialize all elements to true
        boolean[] isPrime = new boolean[r + 1];
        Arrays.fill(isPrime, true);
 
        // Mark 0 and 1 as non-prime
        isPrime[0] = isPrime[1] = false;
 
        // Iterate from 2 to square root of r to find prime
        // numbers
        for (int i = 2; i <= Math.sqrt(r); i++) {
            if (isPrime[i]) {
                // Mark all multiples of the current prime
                // as non-prime
                for (int j = i * i; j <= r; j += i) {
                    isPrime[j] = false;
                }
            }
        }
 
        int sum = 0;
        // Calculate the sum of prime numbers within the
        // range [l, r]
        for (int i = l; i <= r; i++) {
            if (isPrime[i]) {
                sum += i;
            }
        }
 
        return sum;
    }
 
    public static void main(String[] args)
    {
        int l = 4, r = 13;
        // Call the primeSum function and print the result
        System.out.println(primeSum(l, r));
    }
}

                    

Python3

import math
 
def primeSum(l, r):
    isPrime = [True] * (r + 1)
    isPrime[0] = isPrime[1] = False
 
    for i in range(2, math.isqrt(r) + 1):
        if isPrime[i]:
            for j in range(i * i, r + 1, i):
                isPrime[j] = False
 
    primeSum = 0
    for i in range(l, r + 1):
        if isPrime[i]:
            primeSum += i
 
    return primeSum
 
l = 4
r = 13
print(primeSum(l, r))

                    

C#

using System;
using System.Collections.Generic;
 
class GFG {
    static int PrimeSum(int l, int r)
    {
        // Initialize a boolean array to track whether each
        // number is prime or not
        bool[] isPrime = new bool[r + 1];
        for (int i = 2; i <= r; i++) {
            isPrime[i] = true;
        }
 
        // Use the Sieve of Eratosthenes algorithm to mark
        // non-prime numbers
        for (int i = 2; i <= Math.Sqrt(r); i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= r; j += i) {
                    isPrime[j] = false;
                }
            }
        }
 
        int sum = 0;
        for (int i = l; i <= r; i++) {
            if (isPrime[i]) {
                sum += i;
            }
        }
 
        return sum;
    }
 
    static void Main()
    {
        int l = 4, r = 13;
        int sum = PrimeSum(l, r);
        Console.WriteLine(sum);
    }
}

                    

Javascript

function primeSum(l, r) {
    // Initialize an array to track prime numbers
    let isPrime = new Array(r + 1).fill(true);
    isPrime[0] = isPrime[1] = false;
 
    // Sieve of Eratosthenes algorithm to mark non-prime numbers
    for (let i = 2; i <= Math.sqrt(r); i++) {
        if (isPrime[i]) {
            for (let j = i * i; j <= r; j += i) {
                isPrime[j] = false;
            }
        }
    }
 
    let sum = 0;
    // Calculate the sum of prime numbers between l and r
    for (let i = l; i <= r; i++) {
        if (isPrime[i]) {
            sum += i;
        }
    }
 
    return sum;
}
 
// Test the primeSum function
let l = 4, r = 13;
console.log(primeSum(l, r));

                    

Output
36

Time complexity: O(r log log r).
Auxiliary Space: O(r)



Last Updated : 14 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads