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
< ? php function sumodd ( $ n ) { return ( $ n * $ n ) ; } function sumeven ( $ n ) { return ( $ n * ( $ n + 1 ) ) ; } function findSum ( $ num ) { $ sumo = 0 ; $ sume = 0 ; $ x = 1 ; $ cur = 0 ; $ ans = 0 ; while ( $ num > 0 ) { $ inc = 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 ; } $ n = 4 ; echo findSum ( $ n ) ; ? >