Sum of every Kâ €™ th prime number in an array | Javascript implementation of the approach ; 0 and 1 are not prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; compute the answer ; count of primes ; sum of the primes ; traverse the array ; if the number is a prime ; increase the count ; if it is the K 'th prime ; create the sieve
let MAX = 100000 ; let prime = new Array ( MAX + 1 ) . fill ( true ) ; function SieveOfEratosthenes ( ) { prime [ 1 ] = false ; prime [ 0 ] = false ; for ( let p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } function SumOfKthPrimes ( arr , n , k ) { let c = 0 ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { c ++ ; if ( c % k == 0 ) { sum += arr [ i ] ; c = 0 ; } } } document . write ( sum + " " ) ; } SieveOfEratosthenes ( ) ; let arr = new Array ( 2 , 3 , 5 , 7 , 11 ) ; let n = arr . length ; let k = 2 ; SumOfKthPrimes ( arr , n , k ) ;