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 var of this from answer ; function call ; function call
power = Array ( 31 ) . fill ( 0 ) ; pre = Array ( 31 ) . fill ( 0 ) ; function PowerOfTwo ( ) { var x = 1 ; for ( i = 0 ; i < 31 ; i ++ ) { power [ i ] = x ; x *= 2 ; } pre [ 0 ] = 1 ; for ( i = 1 ; i < 31 ; i ++ ) pre [ i ] = pre [ i - 1 ] + power [ i ] ; } function Sum ( n ) { var ans = n * ( n + 1 ) / 2 ; for ( i = 0 ; i < 31 ; i ++ ) { if ( power [ i ] > n ) { ans -= 2 * pre [ i - 1 ] ; break ; } } return ans ; } PowerOfTwo ( ) ; var n = 4 ; document . write ( Sum ( n ) ) ;