Sum of all the prime numbers with the maximum position of set bit â ‰¤ D | C ++ ; Function for Sieve of Eratosthenes ; Function to return the sum of the required prime numbers ; Maximum number of the required range ; Sieve of Eratosthenes ; To store the required sum ; If current element is prime ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( bool prime [ ] , int n ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } int sumPrime ( int d ) { int maxVal = pow ( 2 , d ) - 1 ; bool prime [ maxVal + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; sieve ( prime , maxVal ) ; int sum = 0 ; for ( int i = 2 ; i <= maxVal ; i ++ ) { if ( prime [ i ] ) { sum += i ; } } return sum ; } int main ( ) { int d = 8 ; cout << sumPrime ( d ) ; return 0 ; }