Sum of Semi | C ++ implementation of the approach ; Vector to store the primes ; Create a boolean array " prime [ 0 . . n ] " ; Initialize all prime values to be 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 ; Print all prime numbers ; Function to return the semi - prime sum ; Variable to store the sum of semi - primes ; Iterate over the prime values ; Break the loop once the product exceeds N ; Add valid products which are less than or equal to N each product is a semi - prime number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE vector < ll > pr ; bool prime [ 10000000 + 1 ] ; void sieve ( ll n ) { for ( int i = 2 ; i <= n ; i += 1 ) { prime [ i ] = 1 ; } for ( ll p = 2 ; ( ll ) p * ( ll ) p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( ll i = ( ll ) p * ( ll ) p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( ll p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) pr . push_back ( p ) ; } ll SemiPrimeSum ( ll N ) { ll ans = 0 ; for ( int i = 0 ; i < pr . size ( ) ; i += 1 ) { for ( int j = i ; j < pr . size ( ) ; j += 1 ) { if ( ( ll ) pr [ i ] * ( ll ) pr [ j ] > N ) break ; ans += ( ll ) pr [ i ] * ( ll ) pr [ j ] ; } } return ans ; } int main ( ) { ll N = 6 ; sieve ( N ) ; cout << SemiPrimeSum ( N ) ; return 0 ; }