Sum of decimals that are binary representations of first N natural numbers | Python3 program for the above approach ; Function to find the sum of first N natural numbers represented in binary representation ; Stores the resultant sum ; Iterate until the value of N is greater than 0 ; If N is less than 2 ; Store the MSB position of N ; Iterate in the range [ 1 , x ] and add the contribution of the numbers from 1 to ( 2 ^ x - 1 ) ; Update the value of the cur and add ; Add the cur to ans ; Store the remaining numbers ; Add the contribution by MSB by the remaining numbers ; The next iteration will be repeated for 2 ^ x - 1 ; Print the result ; Driver Code
from math import log2 , pow NEW_LINE MOD = 1000000007 NEW_LINE def sumOfBinaryNumbers ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE one = 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT ans = ( ans + n ) % MOD NEW_LINE break NEW_LINE DEDENT x = int ( log2 ( n ) ) NEW_LINE cur = 0 NEW_LINE add = ( one << ( x - 1 ) ) NEW_LINE for i in range ( 1 , x + 1 , 1 ) : NEW_LINE INDENT cur = ( cur + add ) % MOD NEW_LINE add = ( add * 10 % MOD ) NEW_LINE DEDENT ans = ( ans + cur ) % MOD NEW_LINE rem = n - ( one << x ) + 1 NEW_LINE p = pow ( 10 , x ) NEW_LINE p = ( p * ( rem % MOD ) ) % MOD NEW_LINE ans = ( ans + p ) % MOD NEW_LINE n = rem - 1 NEW_LINE DEDENT print ( int ( ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE sumOfBinaryNumbers ( N ) NEW_LINE DEDENT