Sum of first N natural numbers by taking powers of 2 as negative number | to store power of 2 ; to store presum of the power of 2 's ; function to find power of 2 ; to store power of 2 ; to store pre sum ; Function to find the sum ; first store sum of first n natural numbers . ; find the first greater number than given number then minus double of this from answer ; Driver code ; function call ; function call
power = [ 0 ] * 31 NEW_LINE pre = [ 0 ] * 31 NEW_LINE def PowerOfTwo ( ) : NEW_LINE INDENT x = 1 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT power [ i ] = x NEW_LINE x *= 2 NEW_LINE DEDENT pre [ 0 ] = 1 NEW_LINE for i in range ( 1 , 31 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + power [ i ] NEW_LINE DEDENT DEDENT def Sum ( n ) : NEW_LINE INDENT ans = n * ( n + 1 ) // 2 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT if ( power [ i ] > n ) : NEW_LINE INDENT ans -= 2 * pre [ i - 1 ] NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT PowerOfTwo ( ) NEW_LINE n = 4 NEW_LINE print ( Sum ( n ) ) NEW_LINE DEDENT