Sum of first N natural numbers with all powers of 2 added twice | Function to raise N to the power P and return the value ; Function to calculate the log base 2 of an integer ; Calculate log2 ( N ) indirectly using log ( ) method ; Function to calculate and return the required sum ; Sum of first N natural numbers ; Sum of all powers of 2 up to N ; Driver Code
function power ( N , P ) { return Math . pow ( N , P ) ; } function Log2 ( N ) { let result = ( Math . floor ( Math . log ( N ) / Math . log ( 2 ) ) ) ; return result ; } function specialSum ( n ) { let sum = n * ( n + 1 ) / 2 ; let a = Log2 ( n ) ; sum = sum + power ( 2 , a + 1 ) - 1 ; return sum ; } let n = 4 ; document . write ( specialSum ( n ) + " " ) ;