Given a positive integer N, the task is to calculate the sum of all decimals which can be expressed as binary representations of first N natural numbers.
Examples:
Input: N = 3
Output: 22
Explanation:
The Binary Representation of 1 is 01.
The Binary Representation of 2 is 10.
The Binary Representation of 3 is 11.
Therefore, required sum = 01 + 10 + 11 = 22.Input: N = 5
Output: 223
Naive Approach: The simplest approach to solve the problem is to iterate a loop over the range [1, N] and in each iteration convert the current number to its binary representation and add it to the overall sum. After adding all the numbers, print the sum as the result.Â
Time Complexity: O(N * log(N))
Auxiliary Space: O(32)
Efficient Approach: The above approach can also be optimized by finding the contribution of numbers not having the same most significant bit (MSB) position as N and then find the contribution by the MSB of the rest of the numbers. Follow the steps to solve the problem:
- Initialize a variable, say ans as 0 to store the sum of all the numbers in the binary representation of first N natural numbers.
- Iterate until the value of N is at least 0, and perform the following steps:
- Store the MSB position of the number N in a variable X and store the value of 2(X – 1) in a variable, say A.
- Initialize a variable, say cur as 0 to store the contribution of numbers not having the same MSB position as N.
- Iterate over the range [1, X], and in each iteration, add A to the variable cur and then multiply A by 10.
- After the above steps, add the value of cur to ans and store the remaining elements in variable rem as (N – 2X + 1).
- Add the contribution by the MSB of the rest of the numbers by adding (rem * 10X) to the ans.
- Update the value of N to (rem – 1) for the next iteration.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach Â
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; Â
// Function to find the sum of first // N natural numbers represented // in binary representation void sumOfBinaryNumbers( int n) {     // Stores the resultant sum     int ans = 0; Â
    int one = 1; Â
    // Iterate until the value of     // N is greater than 0     while (1) { Â
        // If N is less than 2         if (n <= 1) {             ans = (ans + n) % MOD;             break ;         } Â
        // Store the MSB position of N         int x = log2(n); Â
        int cur = 0;         int add = (one << (x - 1)); Â
        // Iterate in the range [1, x]         // and add the contribution of         // the numbers from 1 to (2^x-1)         for ( int i = 1; i <= x; i++) { Â
            // Update the value of the             // cur and add             cur = (cur + add) % MOD;             add = (add * 10 % MOD);         } Â
        // Add the cur to ans         ans = (ans + cur) % MOD; Â
        // Store the remaining numbers         int rem = n - (one << x) + 1; Â
        // Add the contribution by MSB         // by the remaining numbers         int p = pow (10, x);         p = (p * (rem % MOD)) % MOD;         ans = (ans + p) % MOD; Â
        // The next iteration will         // be repeated for 2^x - 1         n = rem - 1;     } Â
    // Print the result     cout << ans; } Â
// Driver Code int main() { Â Â Â Â int N = 3; Â Â Â Â sumOfBinaryNumbers(N); Â
    return 0; } |
Java
/// Java program for the above approach import java.io.*; import java.lang.*; Â
class GFG { Â Â Â Â static final int MOD = 1000000007 ; Â
    // Function to find the sum of first     // N natural numbers represented     // in binary representation     static void sumOfBinaryNumbers( int n)     { Â
        // Stores the resultant sum         int ans = 0 ; Â
        int one = 1 ; Â
        // Iterate until the value of         // N is greater than 0         while ( true ) { Â
            // If N is less than 2             if (n <= 1 ) {                 ans = (ans + n) % MOD;                 break ;             } Â
            // Store the MSB position of N             int x = ( int )(Math.log(n) / Math.log( 2 )); Â
            int cur = 0 ;             int add = ( int )(Math.pow( 2 , (x - 1 ))); Â
            // Iterate in the range [1, x]             // and add the contribution of             // the numbers from 1 to (2^x-1)             for ( int i = 1 ; i <= x; i++) { Â
                // Update the value of the                 // cur and add                 cur = (cur + add) % MOD;                 add = (add * 10 % MOD);             } Â
            // Add the cur to ans             ans = (ans + cur) % MOD; Â
            // Store the remaining numbers             int rem = n - ( int )(Math.pow( 2 , x)) + 1 ; Â
            // Add the contribution by MSB             // by the remaining numbers             int p = ( int )Math.pow( 10 , x);             p = (p * (rem % MOD)) % MOD;             ans = (ans + p) % MOD; Â
            // The next iteration will             // be repeated for 2^x - 1             n = rem - 1 ;         } Â
        // Print the result         System.out.println(ans);     } Â
    // Driver Code     public static void main(String[] args)     {         int N = 3 ;              sumOfBinaryNumbers(N);     } } Â
// This code is contributed by Dharanendra L V |
Python3
# Python3 program for the above approach from math import log2, pow Â
MOD = 1000000007 Â
# Function to find the sum of first # N natural numbers represented # in binary representation def sumOfBinaryNumbers(n):          # Stores the resultant sum     ans = 0 Â
    one = 1 Â
    # Iterate until the value of     # N is greater than 0     while ( 1 ):                  # If N is less than 2         if (n < = 1 ):             ans = (ans + n) % MOD             break Â
        # Store the MSB position of N         x = int (log2(n)) Â
        cur = 0         add = (one << (x - 1 )) Â
        # Iterate in the range [1, x]         # and add the contribution of         # the numbers from 1 to (2^x-1)         for i in range ( 1 , x + 1 , 1 ):                          # Update the value of the             # cur and add             cur = (cur + add) % MOD             add = (add * 10 % MOD) Â
        # Add the cur to ans         ans = (ans + cur) % MOD Â
        # Store the remaining numbers         rem = n - (one << x) + 1 Â
        # Add the contribution by MSB         # by the remaining numbers         p = pow ( 10 , x)         p = (p * (rem % MOD)) % MOD         ans = (ans + p) % MOD Â
        # The next iteration will         # be repeated for 2^x - 1         n = rem - 1 Â
    # Print the result     print ( int (ans)) Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â Â Â Â Â Â N = 3 Â Â Â Â Â Â Â Â Â sumOfBinaryNumbers(N) Â
# This code is contributed by SURENDRA_GANGWAR |
C#
// C# program for the above approach using System; class GFG{ Â Â Â Â Â const int MOD = 1000000007; Â
// Function to find the sum of first // N natural numbers represented // in binary representation static void sumOfBinaryNumbers( int n) {          // Stores the resultant sum     int ans = 0; Â
    int one = 1; Â
    // Iterate until the value of     // N is greater than 0     while ( true )     {                  // If N is less than 2         if (n <= 1)         {             ans = (ans + n) % MOD;             break ;         } Â
        // Store the MSB position of N         int x = ( int )Math.Log(n, 2); Â
        int cur = 0;         int add = (one << (x - 1)); Â
        // Iterate in the range [1, x]         // and add the contribution of         // the numbers from 1 to (2^x-1)         for ( int i = 1; i <= x; i++)         {                          // Update the value of the             // cur and add             cur = (cur + add) % MOD;             add = (add * 10 % MOD);         } Â
        // Add the cur to ans         ans = (ans + cur) % MOD; Â
        // Store the remaining numbers         int rem = n - (one << x) + 1; Â
        // Add the contribution by MSB         // by the remaining numbers         int p = ( int )Math.Pow(10, x);         p = (p * (rem % MOD)) % MOD;         ans = (ans + p) % MOD; Â
        // The next iteration will         // be repeated for 2^x - 1         n = rem - 1;     } Â
    // Print the result     Console.WriteLine(ans); } Â
// Driver Code public static void Main() { Â Â Â Â int N = 3; Â Â Â Â Â Â Â Â Â sumOfBinaryNumbers(N); } } Â
// This code is contributed by ukasp |
Javascript
<script> Â
// JavaScript program to implement // the above approach Â
let MOD = 1000000007;       // Function to find the sum of first     // N natural numbers represented     // in binary representation     function sumOfBinaryNumbers(n)     {           // Stores the resultant sum         let ans = 0;           let one = 1;           // Iterate until the value of         // N is greater than 0         while ( true ) {               // If N is less than 2             if (n <= 1) {                 ans = (ans + n) % MOD;                 break ;             }               // Store the MSB position of N             let x = Math.floor(Math.log(n) / Math.log(2));               let cur = 0;             let add = Math.floor(Math.pow(2, (x - 1)));               // Iterate in the range [1, x]             // and add the contribution of             // the numbers from 1 to (2^x-1)             for (let i = 1; i <= x; i++) {                   // Update the value of the                 // cur and add                 cur = (cur + add) % MOD;                 add = (add * 10 % MOD);             }               // Add the cur to ans             ans = (ans + cur) % MOD;               // Store the remaining numbers             let rem = n - Math.floor(Math.pow(2, x)) + 1;               // Add the contribution by MSB             // by the remaining numbers             let p = Math.floor(Math.pow(10, x));             p = (p * (rem % MOD)) % MOD;             ans = (ans + p) % MOD;               // The next iteration will             // be repeated for 2^x - 1             n = rem - 1;         }           // Print the result          document.write(ans);     } Â
// Driver code Â
    let N = 3;           sumOfBinaryNumbers(N);      </script> |
22
Â
Time Complexity: O(log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!