Open In App

Sum of consecutive bit differences of first N non-negative integers

Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N, the task is to find out the sum of all consecutive bit differences from 0 to N. 
Note: If the bit length is different for two numbers like(3, 4) then append 0 at the beginning (011, 100). 
Examples:

Input: N = 3 
Output:
Explanation: 
Bit differences of (0, 1) + (1, 2) + (2, 3) = 1 + 2 + 1 = 4.
Input: N = 7 
Output: 11

Naive Approach: 
The simplest approach is to compare the two consecutive values within the range bitwise and find out by how many bits both these numbers differ. Add this bit difference to the sum. The final sum thus obtained is the required solution. 
Time Complexity: O(N)
Approach: 
Following observations are to be made to optimize the above solution:

  • The consecutive bit differences of numbers follow a pattern i.e. every value X which is equal to (2i) has a bit difference of (i + 1) with its previous number and the (2i – 1) numbers above X and (2i – 1) numbers below X follow the same pattern.
  • For X = 4 (22), i = 2 has a bit difference is (2 + 1) and the numbers (1, 2, 3) and (5, 6, 7) follow the same bit difference pattern.
For X = 4, the pattern is as follows:
NUM   BIT Diff
1     1(0, 1)
2     2(1, 2)
3     1(2, 3)
4     3(3, 4)
5     1(4, 5)
6     2(5, 6)
7     1(6, 7)

Follow the steps below to solve the problem:

  • For every N, find the nearest number less than or equal to N, which is a power of 2. Say that number is M.
  • For all the numbers less than M, the below recursive approach can be used to find out the sum of the consecutive bit differences.

 
 

Count(i) = (i + 1) + 2 * Count(i – 1) 
where i is the exponent of the nearest power of 2.

 

  • Initialize an array of size 65(0 – based indexing) to store the values obtained while using the recursive function Count(), so that in future, if the same values of Count() are needed, they can be directly obtained without recursively calling the Count() function to save time.
  • Repeat the same process for the remaining numbers which are greater than M by using the below formula.

 
 

Sum = Sum + (i+1) + Count(i-1)

 

For example: 
For N = 10, calculate the sum for the nearest power of 2 that is M = 8, using Count(3) and then repeat the process for remaining numbers greater than 8.
Below is the implementation of the above approach:

C++




// C++ program for the above problem
#include <bits/stdc++.h>
using namespace std;
 
long long a[65] = { 0 };
 
// Recursive function to count
// the sum of bit differences
// of numbers from 1 to
// pow(2, (i+1)) - 1
long long Count(int i)
{
    // base cases
    if (i == 0)
        return 1;
 
    else if (i < 0)
        return 0;
 
    // Recursion call if the sum
    // of bit difference of numbers
    // around i are not calculated
    if (a[i] == 0) {
        a[i] = (i + 1) + 2 * Count(i - 1);
        return a[i];
    }
 
    // return the sum of bit
    // differences if already
    // calculated
    else
        return a[i];
}
 
// Function to calculate the
// sum of bit differences up to N
long long solve(long long n)
{
    long long i, sum = 0;
 
    while (n > 0) {
 
        // nearest smaller power
        // of 2
        i = log2(n);
 
        // remaining numbers
        n = n - pow(2, i);
 
        // calculate the count
        // of bit diff
        sum = sum + (i + 1) + Count(i - 1);
    }
    return sum;
}
 
// Driver code
int main()
{
    long long n = 7;
    cout << solve(n) << endl;
    return 0;
}


Java




// Java program for the above problem
import java.util.*;
class GFG{
   
static int a[] = new int[65];
   
// Recursive function to count
// the sum of bit differences
// of numbers from 1 to
// pow(2, (i+1)) - 1
static int Count(int i)
{
     
    // base cases
    if (i == 0)
        return 1;
  
    else if (i < 0)
        return 0;
  
    // Recursion call if the sum
    // of bit difference of numbers
    // around i are not calculated
    if (a[i] == 0)
    {
        a[i] = (i + 1) + 2 * Count(i - 1);
        return a[i];
    }
  
    // return the sum of bit
    // differences if already
    // calculated
    else
        return a[i];
}
  
// Function to calculate the
// sum of bit differences up to N
static int solve(int n)
{
    int i, sum = 0;
  
    while (n > 0)
    {
  
        // nearest smaller power
        // of 2
        i = (int)(Math.log(n) / Math.log(2));
 
  
        // remaining numbers
        n = n - (int)Math.pow(2, i);
  
        // calculate the count
        // of bit diff
        sum = sum + (i + 1) + Count(i - 1);
    }
    return sum;
}
  
// Driver code
public static void main(String[] args)
{
    int  n = 7;
    System.out.println(solve(n));
}
}
 
// This code is contributed by rock_cool


Python3




# Python3 program for the above problem
import math
 
a = [0] * 65
 
# Recursive function to count
# the sum of bit differences
# of numbers from 1 to
# pow(2, (i+1)) - 1
def Count(i):
     
    # Base cases
    if (i == 0):
        return 1
 
    elif (i < 0):
        return 0
 
    # Recursion call if the sum
    # of bit difference of numbers
    # around i are not calculated
    if (a[i] == 0):
        a[i] = (i + 1) + 2 * Count(i - 1)
        return a[i]
 
    # Return the sum of bit
    # differences if already
    # calculated
    else:
        return a[i]
 
# Function to calculate the
# sum of bit differences up to N
def solve(n):
     
    sum = 0
 
    while (n > 0):
 
        # Nearest smaller power
        # of 2
        i = int(math.log2(n))
 
        # Remaining numbers
        n = n - pow(2, i)
 
        # Calculate the count
        # of bit diff
        sum = sum + (i + 1) + Count(i - 1)
     
    return sum
 
# Driver code
n = 7
 
print(solve(n))
 
# This code is contributed by sanjoy_62


C#




// C# program for the above problem
using System;
class GFG{
 
static int []a = new int[65];
 
// Recursive function to count
// the sum of bit differences
// of numbers from 1 to
// pow(2, (i+1)) - 1
static int Count(int i)
{
     
    // base cases
    if (i == 0)
        return 1;
 
    else if (i < 0)
        return 0;
 
    // Recursion call if the sum
    // of bit difference of numbers
    // around i are not calculated
    if (a[i] == 0)
    {
        a[i] = (i + 1) + 2 * Count(i - 1);
        return a[i];
    }
 
    // return the sum of bit
    // differences if already
    // calculated
    else
        return a[i];
}
 
// Function to calculate the
// sum of bit differences up to N
static int solve(int n)
{
    int i, sum = 0;
 
    while (n > 0)
    {
 
        // nearest smaller power
        // of 2
        i = (int)(Math.Log(n) / Math.Log(2));
 
 
        // remaining numbers
        n = n - (int)Math.Pow(2, i);
 
        // calculate the count
        // of bit diff
        sum = sum + (i + 1) + Count(i - 1);
    }
    return sum;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 7;
    Console.Write(solve(n));
}
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
 
    // Javascript program for the above problem
     
    let a = new Array(65);
    a.fill(0);
   
    // Recursive function to count
    // the sum of bit differences
    // of numbers from 1 to
    // pow(2, (i+1)) - 1
    function Count(i)
    {
        // base cases
        if (i == 0)
            return 1;
 
        else if (i < 0)
            return 0;
 
        // Recursion call if the sum
        // of bit difference of numbers
        // around i are not calculated
        if (a[i] == 0) {
            a[i] = (i + 1) + 2 * Count(i - 1);
            return a[i];
        }
 
        // return the sum of bit
        // differences if already
        // calculated
        else
            return a[i];
    }
 
    // Function to calculate the
    // sum of bit differences up to N
    function solve(n)
    {
        let i, sum = 0;
 
        while (n > 0) {
 
            // nearest smaller power
            // of 2
            i = parseInt(Math.log(n) / Math.log(2), 10);
 
            // remaining numbers
            n = n - parseInt(Math.pow(2, i), 10);
 
            // calculate the count
            // of bit diff
            sum = sum + (i + 1) + Count(i - 1);
        }
        return sum;
    }
 
    let n = 7;
    document.write(solve(n));
     
</script>


Output: 

11

 

Time Complexity: O(log(N)) 
Auxiliary Space: O(1)
 

 



Last Updated : 01 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads