Find the sum of prime numbers in the Kth array | Javascript implementation of the approach \ ; To store whether a number is prime or not ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to return the sum of primes in the Kth array ; Update vector v to store all the prime numbers upto MAX ; To store the sum of primes in the kth array ; Count of primes which are in the arrays from 1 to k - 1 ; k is the number of primes in the kth array ; A prime has been added to the sum ; Driver code
const MAX = 1000000 ; let prime = new Array ( MAX ) ; function SieveOfEratosthenes ( ) { for ( let i = 0 ; i < MAX ; i ++ ) prime [ i ] = true ; for ( let p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] ) { for ( let i = p * p ; i < MAX ; i += p ) prime [ i ] = false ; } } } function sumPrime ( k ) { SieveOfEratosthenes ( ) ; let v = [ ] ; for ( let i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] ) v . push ( i ) ; } let sum = 0 ; let skip = parseInt ( ( k * ( k - 1 ) ) / 2 ) ; while ( k > 0 ) { sum += v [ skip ] ; skip ++ ; k -- ; } return sum ; } let k = 3 ; document . write ( sumPrime ( k ) ) ;