Sum of the first N Prime numbers | C ++ 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 ; Driver code ; create the sieve ; find the value of 1 st n prime numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  10000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } int solve ( int n ) { int count = 0 , num = 1 ; long long int sum = 0 ; while ( count < n ) { if ( prime [ num ] ) { sum += num ; count ++ ; } num ++ ; } return sum ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 4 ; cout << " Sum ▁ of ▁ 1st ▁ N ▁ prime ▁ numbers ▁ are ▁ : " << solve ( n ) ; return 0 ; }