Sum of all the prime numbers in a given range | Suppose the constraint is N <= 1000 ; Declare an array for dynamic approach ; Method to compute the array ; Declare an extra array as arr ; Iterate the loop till sqrt ( n ) Time Complexity is O ( log ( n ) X sqrt ( n ) ) ; if ith element of arr is 0 i . e . marked as prime ; mark all of it 's multiples till N as non-prime  by setting the locations to 1 ; Update the array ' dp ' with the running sum of prime numbers within the range [ 1 , N ] Time Complexity is O ( n ) ; Here , dp [ i ] is the sum of all the prime numbers within the range [ 1 , i ] ; Driver code ; Compute dp
let N = 1000 ; let dp = new Array ( N + 1 ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = 0 ; } 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 ; for ( let i = 2 ; i <= Math . ceil ( Math . sqrt ( N ) + 1 ) ; i ++ ) if ( arr [ i ] == 0 ) for ( let j = i * i ; j <= N ; j += i ) arr [ j ] = 1 ; let runningPrimeSum = 0 ; for ( let i = 1 ; i <= N ; i ++ ) { if ( arr [ i ] == 0 ) runningPrimeSum += i ; dp [ i ] = runningPrimeSum ; } } let l = 4 , r = 13 ; sieve ( ) ; document . write ( dp [ r ] - dp [ l - 1 ] ) ;