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 ; function call ; function call
< ? php $ power = array_fill ( 0 , 31 , 0 ) ; $ pre = array_fill ( 0 , 31 , 0 ) ; function PowerOfTwo ( ) { global $ power , $ pre ; $ 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 ) { global $ power , $ pre ; $ ans = $ n * ( $ n + 1 ) / 2 ; for ( $ i = 0 ; $ i < 31 ; $ i ++ ) if ( $ power [ $ i ] > $ n ) { $ ans -= 2 * $ pre [ $ i - 1 ] ; break ; } return $ ans ; } PowerOfTwo ( ) ; $ n = 4 ; print ( Sum ( $ n ) ) ; ? >