# Sum of all the prime numbers with the maximum position of set bit ≤ D

Given an integer D, the task is to find the sum of all the prime numbers whose maximum position of set bits (the farthest set bit from the right) is less than or equal to D
Note: 2 in binary is 10 and the maximum set bit position is 2. 7 in binary is 111, maximum set bit position is 3.

Examples:

Input: D = 3
Output: 17
2, 3, 5 and 7 are the only primes
which satisfy the given condition.
Input: D = 8
Output: 6081

Brute Force Approach:

The brute force approach involves checking each number up to 2^D – 1 for primality and then checking its binary representation for the maximum set bit position.

Here’s the approach:

1. Initialize a variable ans to 0.
2. Loop through each number i from 2 to 2^D – 1.
3. For each number i, check if it is prime using a primality test such as trial division.
4. If the number i is prime, convert it to binary and find the maximum set bit position using the bit manipulation techniques.
5. If the maximum set bit position is less than or equal to D, add the number i to ans.
6. Return the value of ans.

## C++

 `#include ``using` `namespace` `std;` `bool` `isPrime(``int` `n) {``    ``if` `(n <= 1) {``        ``return` `false``;``    ``}``    ``for` `(``int` `i = 2; i <= ``sqrt``(n); i++) {``        ``if` `(n % i == 0) {``            ``return` `false``;``        ``}``    ``}``    ``return` `true``;``}` `int` `sumPrime(``int` `d) {``    ``int` `n = (1 << d) - 1;``    ``int` `ans = 0;``    ``for` `(``int` `i = 2; i <= n; i++) {``        ``if` `(isPrime(i)) {``            ``int` `num = i;``            ``int` `msb = 0;``            ``while` `(num > 0) {``                ``msb++;``                ``num >>= 1;``            ``}``            ``if` `(msb <= d) {``                ``ans += i;``            ``}``        ``}``    ``}``    ``return` `ans;``}` `int` `main() {``    ``int` `d = 8;``    ``cout << sumPrime(d) << endl;``    ``return` `0;``}`

## Java

 `import` `java.lang.Math;` `public` `class` `Main {``    ``// Define a function to check if a number is prime``    ``static` `boolean` `isPrime(``int` `n) {``        ``if` `(n <= ``1``) {``            ``return` `false``;``        ``}``        ``for` `(``int` `i = ``2``; i <= Math.sqrt(n); i++) {``            ``if` `(n % i == ``0``) {``                ``return` `false``;``            ``}``        ``}``        ``return` `true``;``    ``}` `    ``// Define a function to find the sum of all primes whose binary representation has at most d digits``    ``static` `int` `sumPrime(``int` `d) {``        ``int` `n = (``1` `<< d) - ``1``;``        ``int` `ans = ``0``;``        ``for` `(``int` `i = ``2``; i <= n; i++) {``            ``if` `(isPrime(i)) {``                ``int` `num = i;``                ``int` `msb = ``0``;``                ``while` `(num > ``0``) {``                    ``msb++;``                    ``num >>= ``1``;``                ``}``                ``if` `(msb <= d) {``                    ``ans += i;``                ``}``            ``}``        ``}``        ``return` `ans;``    ``}` `    ``public` `static` `void` `main(String[] args) {``        ``int` `d = ``8``;``        ``System.out.println(sumPrime(d));``    ``}``}`

## Python3

 `import` `math` `# Function to check if a given number is prime or not``def` `isPrime(n):``    ``if` `n <``=` `1``:``        ``return` `False``    ``for` `i ``in` `range``(``2``, ``int``(math.sqrt(n)) ``+` `1``):``        ``if` `n ``%` `i ``=``=` `0``:``            ``return` `False``    ``return` `True` `# Function to calculate the sum of all prime numbers less than 2^d``def` `sumPrime(d):``    ``n ``=` `(``1` `<< d) ``-` `1``    ``ans ``=` `0``    ``for` `i ``in` `range``(``2``, n ``+` `1``):``        ``if` `isPrime(i):``            ``num ``=` `i``            ``msb ``=` `0``            ``while` `num > ``0``:``                ``msb ``+``=` `1``                ``num >>``=` `1``            ``if` `msb <``=` `d:``                ``ans ``+``=` `i``    ``return` `ans` `# Example usage of the functions``d ``=` `8``print``(sumPrime(d))`

## C#

 `using` `System;` `class` `MainClass {``    ``// Check if a given number is prime``    ``static` `bool` `IsPrime(``int` `n)``    ``{``        ``if` `(n <= 1) { ``// 1 is not prime``            ``return` `false``;``        ``}``        ``for` `(``int` `i = 2; i <= Math.Sqrt(n);``             ``i++) { ``// Check divisors up to sqrt(n)``            ``if` `(n % i == 0) {``                ``return` `false``; ``// n is divisible by i, so``                              ``// it's not prime``            ``}``        ``}``        ``return` `true``; ``// n is only divisible by 1 and itself,``                     ``// so it's prime``    ``}` `    ``// Compute the sum of all prime numbers with binary``    ``// representation up to d bits``    ``static` `int` `SumPrime(``int` `d)``    ``{``        ``int` `n = (1 << d)``                ``- 1; ``// Maximum number with d binary digits``        ``int` `ans = 0; ``// Initialize sum to zero``        ``for` `(``int` `i = 2; i <= n;``             ``i++) { ``// Check all numbers from 2 to n``            ``if` `(IsPrime(i)) { ``// If i is prime``                ``int` `num = i;``                ``int` `msb = 0;``                ``while` `(num > 0) { ``// Count the number of``                                  ``// binary digits in i``                    ``msb++;``                    ``num >>= 1;``                ``}``                ``if` `(msb <= d) { ``// If i has at most d binary``                                ``// digits``                    ``ans += i; ``// Add i to the sum``                ``}``            ``}``        ``}``        ``return` `ans; ``// Return the final sum``    ``}` `    ``static` `void` `Main()``    ``{``        ``int` `d = 8; ``// Set the number of binary digits to 8``        ``Console.WriteLine(SumPrime(``            ``d)); ``// Compute and print the sum of primes``    ``}``}``// This code is contributed by sarojmcy2e`

## Javascript

 `// Function to check if a given number is prime or not``function` `isPrime(n) {``    ``if` `(n <= 1) {``        ``return` `false``;``    ``}``    ``for` `(let i = 2; i <= Math.sqrt(n); i++) {``        ``if` `(n % i == 0) {``            ``return` `false``;``        ``}``    ``}``    ``return` `true``;``}` `// Function to calculate the sum of all prime numbers less than 2^d``function` `sumPrime(d) {``    ``let n = (1 << d) - 1;``    ``let ans = 0;``    ``for` `(let i = 2; i <= n; i++) {``        ``if` `(isPrime(i)) {``            ``let num = i;``            ``let msb = 0;``            ``while` `(num > 0) {``                ``msb++;``                ``num >>= 1;``            ``}``            ``if` `(msb <= d) {``                ``ans += i;``            ``}``        ``}``    ``}``    ``return` `ans;``}` `// Example usage of the functions``let d = 8;``console.log(sumPrime(d));`

Output
`6081`

Time Complexity: O(2^D * D * sqrt(N))
Auxiliary Space: O(1)

Approach: The maximum number which satisfies the given condition is 2D – 1. So, generate all prime numbers using Sieve of Eratosthenes up to 2D – 1 then find the sum of all the prime numbers in the same range.

Below is the implementation of the above approach:

## C++

 `// C++ ``#include ``using` `namespace` `std;` `// Function for Sieve of Eratosthenes``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``;``        ``}``    ``}``}` `// Function to return the sum of``// the required prime numbers``int` `sumPrime(``int` `d)``{` `    ``// Maximum number of the required range``    ``int` `maxVal = ``pow``(2, d) - 1;` `    ``// Sieve of Eratosthenes``    ``bool` `prime[maxVal + 1];``    ``memset``(prime, ``true``, ``sizeof``(prime));``    ``sieve(prime, maxVal);` `    ``// To store the required sum``    ``int` `sum = 0;` `    ``for` `(``int` `i = 2; i <= maxVal; i++) {` `        ``// If current element is prime``        ``if` `(prime[i]) {``            ``sum += i;``        ``}``    ``}` `    ``return` `sum;``}` `// Driver code``int` `main()``{``    ``int` `d = 8;` `    ``cout << sumPrime(d);` `    ``return` `0;``}`

## Java

 `// Java implementation of the approach``import` `java.util.*;` `class` `GFG ``{` `// Function for Sieve of Eratosthenes``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``;``        ``}``    ``}``}` `// Function to return the sum of``// the required prime numbers``static` `int` `sumPrime(``int` `d)``{` `    ``// Maximum number of the required range``    ``int` `maxVal = (``int``) (Math.pow(``2``, d) - ``1``);` `    ``// Sieve of Eratosthenes``    ``boolean` `[]prime = ``new` `boolean``[maxVal + ``1``];``    ``Arrays.fill(prime, ``true``);``    ``sieve(prime, maxVal);` `    ``// To store the required sum``    ``int` `sum = ``0``;` `    ``for` `(``int` `i = ``2``; i <= maxVal; i++)``    ``{` `        ``// If current element is prime``        ``if` `(prime[i]) ``        ``{``            ``sum += i;``        ``}``    ``}``    ``return` `sum;``}` `// Driver code``public` `static` `void` `main(String[] args) ``{``    ``int` `d = ``8``;` `    ``System.out.println(sumPrime(d));``}``}` `// This code is contributed by PrinciRaj1992`

## Python 3

 `# Python 3 implementation of the approach``from` `math ``import` `sqrt, ``pow` `# Function for Sieve of Eratosthenes``def` `sieve(prime, n):``    ``prime[``0``] ``=` `False``    ``prime[``1``] ``=` `False``    ``for` `p ``in` `range``(``2``, ``int``(sqrt(n)) ``+` `1``, ``1``):``        ``if` `(prime[p] ``=``=` `True``):``            ``for` `i ``in` `range``(p ``*` `p, n ``+` `1``, p):``                ``prime[i] ``=` `False` `# Function to return the sum of``# the required prime numbers``def` `sumPrime(d):``    ` `    ``# Maximum number of the required range``    ``maxVal ``=` `int``(``pow``(``2``, d)) ``-` `1``;` `    ``# Sieve of Eratosthenes``    ``prime ``=` `[``True` `for` `i ``in` `range``(maxVal ``+` `1``)]``    ` `    ``sieve(prime, maxVal)` `    ``# To store the required sum``    ``sum` `=` `0` `    ``for` `i ``in` `range``(``2``, maxVal ``+` `1``, ``1``):``        ` `        ``# If current element is prime``        ``if` `(prime[i]):``            ``sum` `+``=` `i` `    ``return` `sum` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``d ``=` `8` `    ``print``(sumPrime(d))` `# This code is contributed by Surendra_Gangwar`

## C#

 `// C# implementation of the approach``using` `System;``using` `System.Linq;` `class` `GFG ``{` `// Function for Sieve of Eratosthenes``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``;``        ``}``    ``}``}` `// Function to return the sum of``// the required prime numbers``static` `int` `sumPrime(``int` `d)``{` `    ``// Maximum number of the required range``    ``int` `maxVal = (``int``) (Math.Pow(2, d) - 1);` `    ``// Sieve of Eratosthenes``    ``Boolean []prime = ``new` `Boolean[maxVal + 1];``    ` `    ``for` `(``int` `i = 0; i <= maxVal; i++)``        ``prime.SetValue(``true``,i);``    ``sieve(prime, maxVal);` `    ``// To store the required sum``    ``int` `sum = 0;` `    ``for` `(``int` `i = 2; i <= maxVal; i++)``    ``{` `        ``// If current element is prime``        ``if` `(prime[i]) ``        ``{``            ``sum += i;``        ``}``    ``}``    ``return` `sum;``}` `// Driver code``public` `static` `void` `Main(String[] args) ``{``    ``int` `d = 8;` `    ``Console.WriteLine(sumPrime(d));``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``

Output
`6081`

Time Complexity: O(sqrt(2d))
Auxiliary Space: O(2d)

Previous
Next
Share your thoughts in the comments
Similar Reads