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