Sum of the first N Prime numbers | javascript implementation of above solution ; 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 ; Set all multiples of p to non - prime ; find the sum of 1 st N prime numbers ; count of prime numbers ; sum of prime numbers ; if the number is prime add it ; increase the count ; get to next number ; create the sieve ; find the value of 1 st n prime numbers
var MAX = 10000 ; var prime = Array . from ( { length : parseInt ( ( MAX + 1.0 ) ) } , ( _ , i ) => false ) ; function SieveOfEratosthenes ( ) { for ( i = 0 ; i <= MAX ; i ++ ) prime [ i ] = true ; prime [ 1 ] = false ; for ( p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } function solve ( n ) { var count = 0 , num = 1 ; var sum = 0 ; while ( count < n ) { if ( prime [ num ] ) { sum += num ; count ++ ; } num ++ ; } return parseInt ( sum ) ; } SieveOfEratosthenes ( ) ; var n = 4 ; document . write ( " " + solve ( n ) ) ;