Sum of all the prime numbers with the maximum position of set bit â ‰¤ D | Java implementation of the approach ; 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
import java . util . * ; class GFG { static void sieve ( boolean 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 ; } } } static int sumPrime ( int d ) { int maxVal = ( int ) ( Math . pow ( 2 , d ) - 1 ) ; boolean [ ] prime = new boolean [ maxVal + 1 ] ; Arrays . fill ( prime , true ) ; sieve ( prime , maxVal ) ; int sum = 0 ; for ( int i = 2 ; i <= maxVal ; i ++ ) { if ( prime [ i ] ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int d = 8 ; System . out . println ( sumPrime ( d ) ) ; } }