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
def sumodd ( n ) : NEW_LINE INDENT return ( n * n ) NEW_LINE DEDENT def sumeven ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) NEW_LINE DEDENT def findSum ( num ) : NEW_LINE INDENT sumo = 0 NEW_LINE sume = 0 NEW_LINE x = 1 NEW_LINE cur = 0 NEW_LINE ans = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT inc = min ( x , num ) NEW_LINE num -= inc NEW_LINE if ( cur == 0 ) : NEW_LINE INDENT ans = ans + sumodd ( sumo + inc ) - sumodd ( sumo ) NEW_LINE sumo += inc NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans + sumeven ( sume + inc ) - sumeven ( sume ) NEW_LINE sume += inc NEW_LINE DEDENT x *= 2 NEW_LINE cur ^= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 4 NEW_LINE print ( findSum ( n ) ) NEW_LINE