Sum of the series 1 , 2 , 4 , 3 , 5 , 7 , 9 , 6 , 8 , 10 , 11 , 13. . till N | Function to find the sum of first N odd numbers ; Function to find the sum of first N even numbers ; Function to overall find the sum of series ; Initial odd numbers ; Initial even numbers ; First power of 2 ; Check for parity for odd / even ; Counts the sum ; Get the minimum out of remaining num or power of 2 ; Decrease that much numbers from num ; If the segment has odd numbers ; Summate the odd numbers By exclusion ; Increase number of odd numbers ; If the segment has even numbers ; Summate the even numbers By exclusion ; Increase number of even numbers ; Next set of numbers ; Change parity for odd / even ; Driver code
function sumodd ( n ) { return ( n * n ) ; } function sumeven ( n ) { return ( n * ( n + 1 ) ) ; } function findSum ( num ) { let sumo = 0 ; let sume = 0 ; let x = 1 ; let cur = 0 ; let ans = 0 ; while ( num > 0 ) { let inc = Math . min ( x , num ) ; num -= inc ; if ( cur == 0 ) { ans = ans + sumodd ( sumo + inc ) - sumodd ( sumo ) ; sumo += inc ; } else { ans = ans + sumeven ( sume + inc ) - sumeven ( sume ) ; sume += inc ; } x *= 2 ; cur ^= 1 ; } return ans ; } let n = 4 ; document . write ( findSum ( n ) ) ;